SpringBoot-获取上下文

SpringBoot-获取上下文

1.创建上下文工具类SpringContextUtil,如下为简单的上下文工具类,可以根据自己的需要添加上下文相关的管理方法。

package com.supre.springboot;

import org.springframework.context.ApplicationContext;

public class SpringContextUtil {
	
	private static ApplicationContext applicationContext;

	//获取上下文
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	//设置上下文
	public static void setApplicationContext(ApplicationContext applicationContext) {
		SpringContextUtil.applicationContext = applicationContext;
	}

	//通过名字获取上下文中的bean
	public static Object getBean(String name){
		return applicationContext.getBean(name);
	}
	
	//通过类型获取上下文中的bean
	public static Object getBean(Class requiredType){
		return applicationContext.getBean(requiredType);
	}

}

2.在Springboot启动类中,向上下文工具类SpringContextUtil中注入applicationContext,如下:

package com.supre.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class App{
	
    public static void main( String[] args ){
        System.out.println( "Hello World!" );
        ApplicationContext app = SpringApplication.run(App.class, args);
        SpringContextUtil.setApplicationContext(app);
    }

}

3.创建测试类TestController.java和Test.java,使用上下文工具类,如下:

package com.supre.springboot;

import org.springframework.stereotype.Component;

@Component
public class Test {

	public String test(String str){
		System.out.println("000000000000"+str);
		return "test1"+str;
	}
	
}
package com.supre.springboot;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

	private Logger logger = Logger.getLogger(TestController.class);
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(String str){
		logger.info("test mesg");
		Test test = (Test) SpringContextUtil.getBean("test");
		Test test2 = (Test) SpringContextUtil.getBean(Test.class);
		//如果未取到着为空
		System.out.println(test); 
		System.out.println(test2);
		return "test"+str;
	}
}

注意:在上下文中能取到相关的bean,需要将bean注册到spring的上下文中,具体关于bean加入spring上下文的配置,参考:《SpringBoot-依赖注入》

 

4.启动SpringBoot启动类,访问:http://localhost:8080/test?str=add,参考控制台打印结果

 

参考地址:https://my.oschina.net/u/2391658/blog/732748






你可能感兴趣的:(java,SpringBoot)