Spring有三种配置方式:
- XML配置
- 注解配置(annotation)
- Java配置
XML配置
最经典
注解配置
Spring 2.0开始引入。
@Service @Component @Repository @Controller
比如
@Component("userDao")
public class userDao{......}
等效于
<bean id="userDao" class="cn.lovepi.***.userDao"/>
Java配置
基于Java类定义Bean配置元数据,其实就是通过Java类定义Spring配置元数据,且直接消除XML配置文件。
具体步骤如下:
- 用@Configuration标记一个类,表示该类将定义Bean的元数据
- 用@Bean标记相应的方法,该方法名默认就是Bean的名称,该方法返回值就是Bean的对象。
- AnnotationConfigApplicationContext或子类进行加载基于Java类的配置
举例子:
pkg com.mytest;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld message() {
return new HelloWorld();
}
}
上面的例子等效于:
<beans>
<bean id="helloWorld" class="com.mytest.HelloWorld" />
</beans>
定义好之后,我们可以通过AnnotationConfigApplicationContext加载到Spring container里面,来测试一下:
public class ConfigurationTest {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld hw = ctx.getBean(HelloWorld.class);
hw.setMessage("hello");
hw.getMessage();
}
}
类似的,我们可以加载多个bean:
public class ConfigurationTest {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
}
reference:
- 入门的tutorial: https://www.tutorialspoint.com/spring/spring_java_based_configuration.htm
- stackoverflow上面关于几种config bean方式的回答:https://stackoverflow.com/questions/35807056/how-many-ways-are-there-to-configure-the-spring-framework-what-are-the-differen
网友评论