基于java的容器注解
@Bean
- @Bean标识一个用于配置和初始化一个由SpringIoC容器管理的新对象的方法,类似XML配置文件的
- 可以在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以)
上一点中,通常使用的是Configuration
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } XML: <beans> <bean id="myService" class="com.acme.service.MyServiceImpl"> </beans>
- 自定义Bean name
- @ImportResource和@Value
- @Bean和@Scope
- 基于泛型的自动装配
Spring对JSR支持的说明
- Spring还支持使用JSR-250@Resource注解的变量或setter方法,这是一种在Java EE 5和6的通用模式,Spring管理的对象也支持这种模式
@Resource有一个name属性,并且默认Spring解释该值作为并注入bean的名称
public class SimpleMovieLister { private MovieFinder movieFinder; @Resource(name="myMovieFinder") public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
如果没有显式地指定@Resource的name,默认的名称是从属性名或者setter方法得出
public class SimpleMovieLister { private MovieFinder movieFinder; @Resource public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; }
- 注解提供的名字被解析为一个bean的名称,这是由ApplicationContext中的CommonAnnotationBeanPostProcessor发现并处理的
@PostConstruct and @PreDestroy
CommonAnnotationBeanPostProcessor不仅能识别JSR-250中的生命周期注解@Resource,在Spring2.5中引入支持初始化回调和销毁回调,前提是CommonAnnotationBeanPostProcessor是Spring的ApplicationContext注册的
public class CachingMovieLister { @PostConstruct public void populateMovieCache() { } @PreDestory public void clearMovieCache() { } }
使JSR330标准注解
- 从Spring3.0开始支持JSR330标准注解(依赖注入注解),其扫描方式与Spring注解一致
- 使用JSR330需要依赖javax.inject包
使用Maven引入方式
<dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>
@Inject
@Inject等效于@Autowired,可以使用于类、属性、方法、构造器
import javax.inject.Inject; public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) { this. movieFinder = movieFinder; } }
@Named
- 如果想使用特定名称进行依赖注入,使用@Named
@Named与@Component是等效的
import javax.inject.Inject; import javax.inject.Named; public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(@Named("main") MovieFInder movieFInder) { this.movieFinder = movieFinder; } } 或 @Named("movieListener") public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFInder movieFInder) { this.movieFinder = movieFinder; } }
- 阿
- 阿
- 阿
- 阿