Spring注解学习_组件注册1_@Configuration与@Bean
传统的xml配置文件注册bean:
<bean id="person" class="com.study.bean.Person" scope="prototype" >
<property name="age" value="${}"></property>
<property name="name" value="zhangsan"></property>
</bean>
通过@Cnfiguration+@Bean的方式,可以给Spring容器中注册组件,取代了传统的xml配置文件,更加灵活便捷。
我们写一个pojo,一个配置类,还有一个配置文件,演示一下@Configuration是如何使用的:

Person:POJO,懒惰起见,能用lombok的地方都用lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
}
MainConfig:注解类
import org.springframework.context.annotation.Configuration;
//配置类=配置文件
@Configuration
public class MainConfig {
//给容器中注册一个bean,其类型为返回值类型,id为方法名
@Bean
public Person person(){
return new Person("小米",12); //有参构造
}
@Bean
public Person person2(){
Person person = new Person();
person.setName("红米");
person.setAge(44);
return person;
}
@Bean("改名") //Bean注解中可设置name,value字段
//或者可写成 @Bean(name="改名",value="改名")
public Person person3(){
return new Person("黑米",12);
}
}
MainTest:
public class MainTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = context.getBean("person", Person.class);
System.out.println(person);
Person person2 = context.getBean("person2", Person.class);
System.out.println(person2);
String[] beanNamesForType = context.getBeanNamesForType(Person.class);
for (String s : beanNamesForType) {
System.out.println(s);
}
}
}
运行结果:

比较两种Bean注册方式:
| 注解 | 配置文件 |
|---|---|
| 在配置类上标注@Configuration | 创建一个.xml文件 |
| 在类中方法上标注@Bean | xml配置文件中添加bean标签 |
| 方法名 | bean标签中的id字段 |
| 方法返回值 | bean标签中的class字段 |
| @Bean(name="",value="") | bean标签中的name,value字段 |
| 方法中用setter为返回对象设值 | |
| @Scope("") | bean标签中设置bean的作用域 |
| @Lazy懒加载,单例懒汉模式 |
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达,邮件至 708801794@qq.com
文章标题:Spring注解学习_组件注册1_@Configuration与@Bean
文章字数:451
本文作者:梅罢葛
发布时间:2020-03-29, 12:14:14
最后更新:2020-03-29, 14:52:17
原始链接:https://qiurungeng.github.io/2020/03/29/Spring%E6%B3%A8%E8%A7%A3%E5%AD%A6%E4%B9%A0-%E7%BB%84%E4%BB%B6%E6%B3%A8%E5%86%8C-Configuration/