从spring3.0开始spring支持JSR-330 的标准注解。主要是javax.inject这个包下的:
下面的例子用@Inject代替@Autowired。完成自动装配:
MovieFinder的代码如下:
package com.timo.demo; import org.springframework.stereotype.Component; @Component
public class MovieFinder {
private String name;
public void findMovies(){
System.out.println("1,2,3");
}
}
SimpleMovieLister的代码如下:
package com.timo.demo; import org.springframework.stereotype.Component; import javax.inject.Inject;
import javax.inject.Provider;
@Component
public class SimpleMovieLister {
@Inject
private Provider<MovieFinder> movieFinder; public void setMovieFinder(Provider<MovieFinder> movieFinder) {
this.movieFinder = movieFinder;
}
public void listMovies(){
movieFinder.get().findMovies();;
}
}
配置类的代码如下:
package com.timo.demo; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackageClasses = DemoAppConfig.class)
public class DemoAppConfig {
}
测试类的代码如下:
package com.timo.demo; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoAppConfig.class);
SimpleMovieLister movieLister = applicationContext.getBean(SimpleMovieLister.class);
movieLister.listMovies();
}
}