在基础中我们应该知道Springboot的整个项目没有application.xml这个东西
那么我们怎么样去手动配置bean呢?就是这个注解 这个注解实际上可以把你当前这个类放到spring容器中
@configuration表示这个类是一个配置类可以放在java的com.**.config目录下(自己建立)
@Configuration public class MyConfig { @Bean public Person person(){//方法名就是bean名 return new Person(); } }
@Bean public Person person(){ return new Person(); }表示注册一个bean
这是无注解的Person
你要使用注解注入Person你需要先在pojoperson上添加注解
@Component
然后正常注入就行
@Autowired @Qualifier("person") private Person person;
手动获取可以这样
ConfigurableApplicationContext run = SpringApplication.run(HelloSpringBootApplication.class, args); String[] beanDefinitionNames = run.getBeanDefinitionNames();//获得springboot容器中所有bean名 for (String name : beanDefinitionNames) { System.out.println(name); }
可以查到你的bean有没有在容器中注册
@Bean("可以给你的Bean起别名")
使用注解注册bean就不能使用配置类再来注册了不然会报错
@Configuration(proxyBeanMethods=true)
//proxyBeanMethods=true这个东西默认是true他可以保证你的bean他在被springboot初始化在容器中后能够保证是唯一单例的 //若是其他的方法去生成或调用这个bean那么springboot会先去容器中检测这个类在不在不在就创建在的话就直接返回这个单例 //这样保证bean单例但会损失性能,但是可以作为其他类的依赖类来使用, //若是false那么每次调用创建出来的都会是新类,但是速度会快