从spring3.0
开始引入了基于java的容器配置方式,可以完全使用Java
而不是XML
文件来定义应用程序。
java方式基本配置
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
@Bean
注释被用于指示一个方法实例,配置和初始化Spring IoC
容器进行管理的对象。熟悉Spring
的<beans/>XML
方式配置的开发人员来说,@Bean
注释和<bean/>
元素具有相同的作用。
@Configuration
标注在类上,相当于把该类作为spring
的xml
配置文件中的<beans>
,作用为:配置spring
容器(应用上下文)
上面的配置等同于下面的XML
配置方式
<beans>
<bean id="userService" class="com.sample.UserService"/>
</beans>
实例化容器
使用AnnotationConfigApplicationContext
实例化Spring
容器。
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService= ctx.getBean(UserService.class);
userService.add();
}
还可以使用AnnotationConfigApplicationContext
的无参数构造函数实例化,然后使用register()
方法进行配置。
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh();
UserService userService= ctx.getBean(UserService.class);
userService.add();
}
启用组件扫描
@Configuration
@ComponentScan(basePackages = "com.sample")
public class AppConfig {
...
}
等同于context:
命名空间中的XML
声明
<beans>
<context:component-scan base-package="com.sample"/>
</beans>
上面配置中,com.sample
的包将被扫描,寻找带有@Component
,@Service
,@Repostroty
注解的类,并且这些类将被注册到容器中。AnnotationConfigApplicationContext
中scan(String…)
方法提供相同的组件扫描功能:
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.sample");
ctx.refresh();
UserService userService= ctx.getBean(UserService.class);
userService.add();
}
博客原文地址:基于Java方式进行容器配置
网友评论