@Configuration容器中注册组件
import boot.bean.Stu; import boot.bean.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 1.配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例 * 2.配置类本身也是组件 * 3.@Configuration中的属性:proxyBeanMethods,设为true:@Configuration(proxyBeanMethods=true),外部无论对配置类中的 * 这个组件注册方法调用多少次都返回之前注册容器中的单例对象。如果为false,则每次调用新new一个对象 */ @Configuration//告诉springboot这是一个配置类 public class MyConfig { @Bean//给容器中添加组件,以方法名作为组件的id,返回类型就是组件类型。返回的值,就是组件在容器中的实例 public User user01(){ return new User("张三",20); } @Bean("tom")//命名组件名为“tom” public Stu stu01(){ return new Stu("汤姆"); } }
public class Stu { private String name; public Stu(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Stu{" + "name='" + name + '\'' + '}'; } }
public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } 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; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
@SpringBootApplication public class MainApplication { public static void main(String[] args) { //返回IOC容器 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); //查看容器里面的组件 String[] names = run.getBeanDefinitionNames(); /*for (String name : names) { System.out.println(name); }*/ //从容器中获取组件 Stu tom1 = run.getBean("tom", Stu.class); tom1.setName("杰瑞"); Stu tom2 = run.getBean("tom", Stu.class); System.out.println(tom2);//Stu{name='杰瑞'} } }