@Configuration
通过@Configuration注解和@Bean注解,我们可以往Spring的IOC容器中注册Bean实例
示例Bean
public class User {
private String name;
private Integer age;
private Pet pet;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", pet=" + pet +
'}';
}
}
public class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Pet{" +
"name='" + name + '\'' +
'}';
}
}
注册Bean实例
@Configuration//告诉SpringBoot这是一个配置类(proxyBeanMethods 默认值也为true)
public class MyConfig {
@Bean(name = "user") //将User的实例注册到Spring的IOC容器中,指定名字为:user
public User getUser() {
User user = new User();
user.setName("ZhangSan");
user.setAge(18);
user.setPet(getPet());
return user;
}
@Bean(name = "pet") //将Pet的实例注册到Spring的IOC容器中,指定名字为:pet
public Pet getPet() {
Pet pet = new Pet();
pet.setName("tom");
return pet;
}
}
测试代码和打印信息
@SpringBootApplication//告诉SpringBoot这是一个SpringBoot运用
public class Boot01HelloApplication {
public static void main(String[] args) {
ConfigurableApplicationContext application = SpringApplication.run(Boot01HelloApplication.class, args);
User user = application.getBean(User.class);
System.out.println(user);
}
}
//打印信息
User{name='ZhangSan', age=18, pet=Pet{name='tom'}}
@Configuration的proxyBeanMethods属性
@Configuration的proxyBeanMethods为true时,外部无论调用多少次组件注册的方法,返回的都是之前注册到IOC容器中的单实例对象
配置文件,指定@Configuration的proxyBeanMethods属性为true(默认值就为true)
@Configuration(proxyBeanMethods = true)//告诉SpringBoot这是一个配置类(proxyBeanMethods 默认值也为true)
public class MyConfig {
@Bean(name = "user") //将User的实例注册到Spring的IOC容器中,指定名字为:user
public User getUser() {
User user = new User();
user.setName("ZhangSan");
user.setAge(18);
user.setPet(getPet());
return user;
}
@Bean(name = "pet") //将Pet的实例注册到Spring的IOC容器中,指定名字为:pet
public Pet getPet() {
Pet pet = new Pet();
pet.setName("tom");
return pet;
}
}
测试示例和打印信息。我们看到我们的myConfig对象其实是一个cgLib的代理对象,我们调用myConfig的getUSer( )方法,无论调用多少次获取到的对象始终是一个对象。这里也很好的解决了组件的依赖问题
@SpringBootApplication//告诉SpringBoot这是一个SpringBoot运用
public class Boot01HelloApplication {
public static void main(String[] args) {
ConfigurableApplicationContext application = SpringApplication.run(Boot01HelloApplication.class, args);
MyConfig myConfig = application.getBean(MyConfig.class);
System.out.println(myConfig);
Pet pet01 = myConfig.getUser().getPet();
Pet pet02 = myConfig.getPet();
System.out.println(pet01 == pet02);
}
}
//打印信息
com.tlh.boot01hello.config.MyConfig$$EnhancerBySpringCGLIB$$2329c56e@3d7cc3cb
true
我们将@Configuration的proxyBeanMethods属性为false,在看打印信息。此时,我们的myConfig的实例就是MyConfig的实例了,而且我们调用myConfig的getPet( )获取的Pet实例也不再是同一个了
com.tlh.boot01hello.config.MyConfig@41e1455d
false