Spring 实践
获取实例
Spring在初始化时容器会根据配置文件初始化所有配置的bean。在使用时有两种常用方法可以在代码中获取实例。
1、@Autowired
系统会自己根据名称、类型去容器里查找对应的类并且注入,前提适用的场景必须是被Spring所扫描到的类,且被注入到容器里。
换句话说就是:
1、被spring扫描到。
<context:component-scan base-package="com.rest.server"/>
2、类被注解标记。
@Service告诉spring容器,这是一个Service类,标识持久层Bean组件,默认情况会自动加载它到spring容器中。
@Autowried注解告诉spring,这个字段需要自动注入
@Scope指定此spring bean的scope是单例
@Repository注解指定此类是一个容器类,是DA层类的实现。标识持久层Bean组件
@Componet:基本注解,标识一个受Spring管理的Bean组件
@Controller:标识表现层Bean组件
2、ApplicationContextAware
在项目中,会遇到一些在非容器环境下还要获取容器组件的情况,比如定时器job,在job我们会有一些数据库操作,业务层调用,这时通过@Autowired这种方式就会报null。这时就得让job获取它所在的容器。
1、spring配置文件中申明
<bean id="SpringBeanUtil" class="com.util.SpringBeanUtil"/>
2、编写SpringBeanUtil
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
private static SpringBeanUtil stools = null;
public synchronized static SpringBeanUtil init() {
if (stools == null) {
stools = new SpringBeanUtil();
}
return stools;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = applicationContext;
}
public synchronized static Object getBean(String beanName) {
return context.getBean(beanName);
}
public synchronized static Object getBean(Class c) {
return context.getBean(c);
}
}
3、代码使用
SendNoticeService sendNoticeService = (SendNoticeService) SpringBeanUtil.getBean(SendNoticeService.class);