在spring里面使用注释必须先开启注释驱动支持<context:annotation-config/>
<aop:aspectj-autoproxy/>开启@AspectJ的注释
- 对Bean的注释
可以用@Component 、@Repository、@Service、@Controller注释类。
@Component 是通用形式。@Repository注释dao @Service注释service @Controller注释action。
需要通过<context:component-scan>扫描到这些注释的类,才会在spring的容器里面初始化。
@Lazy是否延迟加载
@DependsOn定义依赖的bean
@Scope定义作用域
- 对成员变量的注释
@Resource根据name和type进行成员变量的注入。
@Autowired根据类型匹配,@Resource默认是根据name匹配,推荐使用@Resource。
- ApplicationContextAware使用
最后介绍一种在任意类里面获取容器的方法。
写一个类实现ApplicationContext接口,将该类配置到spring容器里面,会自动将ApplicationContext注入到该类里面。代码如下
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
*
*/
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext; // NOSONAR
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
return (T) applicationContext.getBeansOfType(clazz);
}
/**
* 清除applicationContext静态变量.
*/
public static void cleanApplicationContext() {
applicationContext = null;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
}
在任何地方都能调用静态方法getBean获取Ioc容器里面的javabean。