The central artifacts in Spring’s new Java-configuration support are @Configuration-annotated classes and @Bean-annotated methods.
The @Bean annotation is used to indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container. For those familiar with Spring’s<beans/>
XML configuration, the @Bean annotation plays the same role as the<bean/>
element. You can use @Bean-annotated methods with any Spring @Component. However, they are most often used with @Configuration beans.
Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes let inter-bean dependencies be defined by calling other @Bean methods in the same class.
使用Config开发可以省略配置文件。
LiuConfig.java:1
2
3
4
5
6
7
8
9
10
11
12
13// 这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
// @Configuration代表这是一个配置类,就和之前的Beans.xml一样
@Configuration
public class LiuConfig {
// 注册一个bean,相当于之前写的一个bean标签
// 方法的名字就相当于bean标签的id属性
// 方法的返回值,就相当于bean标签中的class属性
@Bean
public User user() {
return new User();
}
}
User.java:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20@Component
public class User {
@Value("XLIU")
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MyTest.java:1
2
3
4
5
6
7
8public class MyTest {
public static void main(String[] args) {
// 如果完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(LiuConfig.class);
User user = applicationContext.getBean("user", User.class);
System.out.println(user.getName());
}
}