spring注入相关知识
程序员文章站
2022-05-23 10:45:16
...
1、@Autowired可以用在controller,service中,但是不可以用在实体model中,用在实体中会出现空指针异常
2、实体中,过滤器中使用注入,可以通过上下文关系获取实体注入,也可以通过@Configuration @Bean注入方法,推荐使用通过上下文获取。
上下文获取实体注入代码如下
@Component
public class application implements ApplicationContextAware {
private static ApplicationContext Application_Context;
/**
* 获取上下文
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Application_Context=applicationContext;
}
/**
* 根据类名注入实体对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return Application_Context.getBean(beanName);
}
/**
* 根据类返回实体对象
* @param beanName
* @param <T>
* @return
*/
public static <T> T getBeanByClass(Class<T> beanName ){
return Application_Context.getBean(beanName);
}
}
实体类Test
public class Test {
private String name;
/*private static TestService test_Service=(TestService)application.getBean("TestService");*/
private static TestService test_Service=(TestService)application.getBeanByClass(TestService.class);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void cs(){
test_Service.test();
}
}
实体类通过过@Configuration @Bean注入方法,这样就可以将TestService 交给spring容器管理,不能直接new TestService()对象调用,这样会造成service里面自动注入的实体为空。
@Configuration
public class Test {
private String name;
private static TestService test_Service;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Bean
public static TestService setTestService() {
Test.test_Service = new TestService();
return test_Service;
}
public static void cs(){
test_Service.test();
}
}
service代码
@Service
public class TestService {
@Autowired
private TestService1 service1;
public void test(){
service1.test();
System.out.println("TestService test()");
}
}
@Service
public class TestService1 {
public void test(){
System.out.println("TestService1 test1()");
}
}