Spring 对Java 配置的支持是由@Configuration 注解和@Bean 注解来实现的。由@Bean 注解的方法将会实例化、配置和初始化一个新对象,这个对象将由Spring 的IOC 容器来管理。@Bean 声明所起到的作用与元素类似。被@Configuration 所注解的类则表示这个类的主要目的是作为bean 定义的资源。被@Configuration 声明的类可以通过在同一个类的内部调用@bean 方法来设置嵌入bean 的依赖关系。
最简单的@Configuration 声明类请参考下面的代码:
@Configuration
public class AppConfig{
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
对于上面的@Beans 配置文件相同的XML 配置文件如下:
<beans>
<bean id="myService" class="com.leon.services.MyServiceImpl"/>
</beans>
上述配置方式的实例化方式如下:利用AnnotationConfigApplicationContext 类进行实例化
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
要使用组件组建扫描,仅需用@Configuration 进行注解即可:
@Configuration
@ComponentScan(basePackages = "com.leon")
public class AppConfig {
}
在上面的例子中,com.gupaoedu 包首先会被扫到,然后再容器内查找被@Component 声明的类,找到后将这些类按照Spring bean 定义进行注册。
如果你要在你的web 应用开发中选用上述的配置的方式的话, 需要用AnnotationConfigWebApplicationContext 类来读取配置文件,可以用来配置Spring 的Servlet 监听器ContrextLoaderListener 或者Spring MVC 的DispatcherServlet。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Web Application</display-name>
<!-- loading spring context start -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-web.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- loading spring context end -->
<!-- springmvc config start -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- springmvc config end -->
</web-app>