4.9 Annotation-based container configuration

注解配置XML配置之前执行,所以后者会覆盖前者。

                      -----Spring Docs

4.9.1 @Required

@Required应用于setter方法,例如:

 1 public class SimpleMovieLister {
 2 
 3   private MovieFinder movieFinder;
 4 
 5   @Required
 6   public void setMovieFinder(MovieFinder movieFinder) {
 7       this.movieFinder = movieFinder;
 8   }
 9 
10   // ...
11 }

@Required只是表明属性必须被设置,否则报异常NullPointerException。

4.9.2 @Autowired

通过 @Autowired的使用来消除 set get方法。

@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 Method(Car car ,Office office) 的入参来创建 Bean。 

4.9.5 @Resource

1 public class SimpleMovieLister {
2 
3   private MovieFinder movieFinder;
4 
5   @Resource(name="myMovieFinder")
6   public void setMovieFinder(MovieFinder movieFinder) {
7       this.movieFinder = movieFinder;
8   }
9 }

如果没有设置name,默认为the field name or setter method

1 public class SimpleMovieLister {
2 
3   private MovieFinder movieFinder;
4 //name "movieFinder" injected
5   @Resource
6   public void setMovieFinder(MovieFinder movieFinder) {
7       this.movieFinder = movieFinder;
8   }
9 }
public class MovieRecommender {
//looks for a bean named customerPreferenceDao
  @Resource
  private CustomerPreferenceDao customerPreferenceDao;
//
  @Resource
  private ApplicationContext context;

  public MovieRecommender() {
  }

  // ...
}

4.9.6 @PostConstruct and @PreDestroy

 

 1 public class CachingMovieLister {
 2 
 3   @PostConstruct
 4   public void populateMovieCache() {
 5       // populates the movie cache upon initialization...
 6   }
 7 
 8   @PreDestroy
 9   public void clearMovieCache() {
10       // clears the movie cache upon destruction...
11   }
12 }

 

4.12 Java-based container configuration(基于java的Spring容器配置)

4.12.1 Basic concepts: @Configuration and @Bean

在别标记为@Configuration的类中配置容器。

the @Bean annotation plays the same role as the <bean/> element.

 

 

 

posted @ 2012-11-09 17:19  siyed  Views(273)  Comments(0Edit  收藏  举报