#############################Configuration使用示例######################################################
@Configuration(proxyBeanMethods = false) public class MyConfig {
@Bean public User user01(){ User zhangsan = new User("zhangsan", 18); zhangsan.setPet(tomcatPet()); return zhangsan; }
@Bean("tom") public Pet tomcatPet(){ return new Pet("tomcat"); } }
################################@Configuration测试代码如下######################################## @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan("com.atguigu.boot") public class MainApplication {
public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
String[] names = run.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); }
Pet tom01 = run.getBean("tom", Pet.class);
Pet tom02 = run.getBean("tom", Pet.class);
System.out.println("组件:"+(tom01 == tom02));
MyConfig bean = run.getBean(MyConfig.class); System.out.println(bean);
User user = bean.user01(); User user1 = bean.user01(); System.out.println(user == user1);
User user01 = run.getBean("user01", User.class); Pet tom = run.getBean("tom", Pet.class);
System.out.println("用户的宠物:"+(user01.getPet() == tom));
} }
|