对于非Service、Controller类,使用@Autowired注入可能会导致对象为空,故可使用ApplicationContextAware类进行注入
新增Bean类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Sc implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.applicationContext == null)
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
添加@Configuration配置
对于非xml配置
@Bean(name = "Sc")
public Sc SpringContextHolder() {
System.err.println("初始化SC");
return new Sc();
}
如果要调用的类也是Bean,需要设置加载顺序,使用@DependsOn("Sc")
注解保证Sc优先初始化
调用
声明要调用的对象,使用Sc.getBean方法,参数写入对象类即可
private BaseSecurityService baseSecurityService = Sc.getBean(BaseSecurityService.class);
文章评论