我们在普通类里如果想调用已经被spring管理的对象,在Spring中,我们会在Controller层使用自动注入的Service层,在Service层使用自动注入的Dao层,如果想在普通的类中使用自动注入Service或者是Dao层时,可以这样做:我们有两种方式:
第一种方法:
public class TestJsoup {
public NewsDao newsdao;
public void initDataTask() throws Exception{
try {
newsdao = ContextUtils.getBeanByClass(NewsDao.class);
List<News> list = newsdao.getNewsInfo(1, 8);
logger.info(list.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 非spring操作时需要使用spring容器已经加载的环境上下文
*/
@Component
public class ContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
ContextUtils.context = context;
}
/**
* 获取spring已经加载的bean对象
* 通过类class获取
*/
public static <T> T getBeanByClass(Class<T> bean) throws Exception {
return context.getBean(bean);
}
/**
* 通过bean id 获取bean
*/
public static Object getBeanById(String beanId) throws Exception {
if (StringUtils.isNotBlank(beanId)) {
return context.getBean(beanId);
}
return null;
}
/* (non-Javadoc)
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("---------------------------");
System.out.println("---------------------------");
System.out.println("---------------------------");
System.out.println("---------------------------");
System.out.println("---------------------------");
ContextUtils.context = applicationContext;
System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+ContextUtils.context+"========");
}
}
第二种方式:
1、在相应的类上加上@Component注解
@Component注解将我们的类实例化到Spring容器中,这样的方式其实就是相当于xml配置文件中的
<bean id="" class=""/>这种方式。
2、使用@Autowired注解注入我们需要的Bean
@Autowired是一个自动装配的注解,它会帮你去Spring容器中查找相应的实现。
3、在相应的类中加入一个init()函数,在init()函数中初始化注入的Bean,这个函数上要加上@PostConstruct注解
@PostConstruct注解是Java EE5之后的规范,它是servlet中的一个生命周期环节,被@PostConstruct注解修饰的方法会在构造函数之后就执行
@Component
public class TestJsoup{
@Autowired
public NewsDao newsdao;
public static TestJsoup testJsoup;
@PostConstruct
public void init() {
testJsoup = this;
testJsoup.newsdao = this.newsdao;
}
public void initDataTask() throws Exception{
try {
List<News> list = testJsoup.newsdao.getNewsInfo(1,8);
logger.info(list.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}