使用annotation配置项目的好处:
1.使用纯java代码,不再需要xml
2.在配置中也可享受OO带来的好处
3.类型安全对重构也能提供良好的支持
4.依旧能享受到所有spring IoC容器提供的功能
例子:
下面是一个典型的spring配置文件(application-config.xml):
<beans>
<bean id="orderService" class="com.acme.OrderService"/>
<constructor-arg ref="orderRepository"/>
</bean>
<bean id="orderRepository" class="com.acme.OrderRepository"/>
<constructor-arg ref="dataSource"/>
</bean>
</beans>
然后你可以像这样使用bean了:
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
OrderService orderService = (OrderService) ctx.getBean("orderService");
-----------------------------------------------------------------------------------
现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:
@Configuration
public class ApplicationConfig{
public @Bean OrderService orderService(){
return new OrderService(orderRepository());
}
public @Bean OrderRepository orderRepository(){
return new OrderRepository(dataSource());
}
public @Bean DataSource dataSource(){
//instantiate and return an new DataSource...
}
}
然后你可以这样使用bean了:
JavaConfigApplicationContext ctx=new JavaConfigApplicationContext(ApplicationConfig.class);
OrderService orderService=ctx.getBean(OrderService.class);
怎样理解@ComponentScan注解:Spring使用@ComponentScan扫描注解包
java code:
@Configuration
@ComponentScan(basePackages=”org.example:,nameGenerator=MyNameGenerator.class)
public class AppConfig{
.....
}
xml写法:
<beans>
<context:component-scan base-package=”org.example”
name-generator=”org.example.MyNameGenerator”/>
</beans>
java code:
1.配置视图控制器
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.apress.prospringmvc.bookstore.web" })
public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/index.htm").setViewName("index");
}
}
2.基于注解的Controller
@Controller
public class IndexController {
@RequestMapping(value = "/index.htm")
public ModelAndView indexPage() {
return new ModelAndView(“index");
}
}
那么对于配置的视图控制器加了@Configuration 和@ComponentScan注解背后会做什么呢?
其实很简单,@ComponentScan告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。
例如,如果你有个类用@Controller注解标识了,那么,如果不加上 @ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器 中,因此你配置的这个Controller也没有意义。