@configuration
@Configuration这个注解作用就是告诉 springboot 这是一个配置类。配置类以及类里的方法都可以作为bean。用@Bean标记
@Configuration 包含 proxyBeanMethods字段,默认值是true。返回前检测是否存在实例,保证为单例模式。若proxyBeanMethods=”false”则直接返回实例
注意是先指定代理Bean,再通过Bean调用方法
实例1:
写两个Bean,user和pet
package com.itheima.bean; public class Pet { String name; public Pet() { } public Pet(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Pet{" + "name='" + name + '\'' + '}'; } } package com.itheima.bean; public class User { String name; int age; Pet pet; public User() { } public User(String name,int age) { this.name = name; this.age = age; } public User(String name, int age, Pet pet) { this.name = name; this.age = age; this.pet = pet; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int 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 + '}'; } }
Bean的配置类:MyConfig.java,通过@Configuration和@Bean指定装配Bean
@Configuration(proxyBeanMethods = false) public class MyConfig { @Bean public User user01(){ User zhangsan = new User("zhangsan", 18); // zhangsan.setPet(pet01()); return zhangsan; } @Bean("tom") public Pet pet01(){ return new Pet("tom"); } }
测试代码:将MyConfig.java作为Bean,将@Configuration(proxyBeanMethod=false),多次调用Bean的方法,比较返回对象是否相等。
@SpringBootApplication 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); // } //这个ProxyBeanMethod居然是先代理MyConfig这个bean, // 再用bean调用其方法,测试bean的方法返回是否相等,我的天! MyConfig bean = run.getBean(MyConfig.class); System.out.println(bean); User user1 = bean.user01(); User user2 = bean.user01(); System.out.println(user1==user2); // 哥直接用run获取对应的 user01 bean,难怪反复测试都返回true // User user01 = run.getBean("user01", User.class); // User user02 = run.getBean("user01", User.class); // System.out.println(user02==user01); } }
标签:name,age,bean,SpringBoot2,User,注解,Configuration,public,String From: https://www.cnblogs.com/Kaelthas/p/17059554.html