一、基础环境搭建
开发环境搭建:https://blog.csdn.net/weixin_45477697/article/details/108252800
二、@Configuration&@Bean
1. 简单配置
- 配置类MainConfig
在/src/main/java/config下创建MainConfig配置类
import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration:表明这是一个配置类:配置类=配置文件
@Configuration
public class MainConfig {
//@Bean: 表明往容器中注册一个bean;类型为方法的返回值类型,id默认为方法名
@Bean
public Person person() {
return new Person("lisi", 20);
}
}
- 测试类MainTest
//创建bean:基于Spring注解方式
@Test
public void test02() {
//使用AnnotationConfigApplicationContext
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
//打印Person类在IOC容器中的id列表
System.out.println(Arrays.asList(applicationContext.getBeanNamesForType(Person.class)));
}
- 测试结果
Person(name=lisi, age=20)
[person]
2. 修改注入bean的id
(1)方式一:修改@Bean注解标注的方法的方法名
- MainConfig配置类
import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration:表明这是一个配置类:配置类=配置文件
@Configuration
public class MainConfig {
//@Bean: 表明往容器中注册一个bean;类型为方法的返回值类型,id默认为方法名
@Bean
public Person person01() {
return new Person("lisi", 20);
}
}
- MainTest测试类
//创建bean:基于Spring注解方式
@Test
public void test02() {
//使用AnnotationConfigApplicationContext
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
//打印Person类在IOC容器中的id列表
System.out.println(Arrays.asList(applicationContext.getBeanNamesForType(Person.class)));
}
- 测试结果
Person(name=lisi, age=20)
[person01]
(2)方式二:@Bean注解自带的value
- MainConfig配置类
import bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration:表明这是一个配置类:配置类=配置文件
@Configuration
public class MainConfig {
//@Bean: 表明往容器中注册一个bean;类型为方法的返回值类型,id默认为方法名
@Bean("personDemo")
public Person person01() {
return new Person("lisi", 20);
}
}
- MainTest测试类
//创建bean:基于Spring注解方式
@Test
public void test02() {
//使用AnnotationConfigApplicationContext
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
//打印Person类在IOC容器中的id列表
System.out.println(Arrays.asList(applicationContext.getBeanNamesForType(Person.class)));
}
- 测试结果
Person(name=lisi, age=20)
[personDemo]
三、总结
@Configuration
标注在类上
表明这是一个配置类,配置类相当于Spring的配置文件
@Bean
标注在方法上
表明往容器中注册一个bean;类型为方法的返回值类型,id默认为方法名
如果要修改id名,可以通过修改方法名或@Bean(id名)
@Configuration和@Bean
结合使用,可以往容器中注入一个Bean
类似于Spring的配置文件中,使用<bean></bean>往容器中注入Bean