版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
@Configuration, @Bean
@Configuration替代了xml配置文件, 表明當(dāng)前類是配置類
@Bean代替了bean標(biāo)簽, 表示想容器中注入對象, 被貼方法的返回值就是注入到容器中的對象, 方法名就是bean的id
代碼:
@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
// 打印容器中bean的名字
String[] names = ctx.getBeanDefinitionNames();
for (String name : names)
{
System.out.println(name);
}
}
}
@Configuration(proxyBeanMethods = true)
public class BeanConfig
{
@Bean
public Person person()
{
Person p = new Person();
return p;
}
}
在@Configuration中proxyBeanMethods 默認(rèn)就是為true的, 表示被@bean注解的方法的代理永遠(yuǎn)開啟, 即使是通過代碼直接調(diào)用; 這里的代理就是指返回從容器中獲取的對象還是直接new
舉個例子:
@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
BeanConfig config = ctx.getBean("beanConfig", BeanConfig.class);
// 直接手動調(diào)用方法, 走不走代理?
Person p1 = config.person();
Person p2 = config.person();
System.out.println(p1 == p2);
}
}
當(dāng)proxyBeanMethods為true時:@Import
該注解的作用也是向容器中注入對象
@Data
public class Pet
{
private String name;
private Integer age;
}
//----------------------
@Import({Pet.class})
@Configuration(proxyBeanMethods = true)
public class BeanConfig
{
@Bean
public Person person()
{
Person p = new Person();
return p;
}
}
@ConditionalOnXXX
該系列注解表示在某種情況成立時, 才進(jìn)行注入
@Import({Pet.class})
@Configuration(proxyBeanMethods = true)
public class BeanConfig
{
// 當(dāng)指定bean在容器中存在時
@ConditionalOnBean(value = {Pet.class})
@Bean
public Person person()
{
Person p = new Person();
return p;
}
}
// ------------------------------------------
@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
Pet pet = ctx.getBean(Pet.class);
System.out.println("pet被注入: " + (pet != null));
Person p = ctx.getBean("person", Person.class);
System.out.println("person被注入: " + (p != null));
}
}
@ImportResource
解決歷史遺留問題, 如果項目中任然有xml配置bean的方式卻又不想挨個遷移, 可以使用該注解直接導(dǎo)入配置文件: @ImportResource("classpath:beans.xml")
@ConfigurationProperties
該注解用于解析.yml/.properties中的配置并將值注入到相關(guān)的bean中, 需要配合@Component或是@EnableConfigurationProperties使用
yml:
pet:
name: aa
age: 5
用法1:
@Data
@Component
@ConfigurationProperties(prefix = "pet")
public class Pet
{
private String name;
private Integer age;
}
獲取bean并打印:
// 去掉component
@Data
@ConfigurationProperties(prefix = "pet")
public class Pet
{
private String name;
private Integer age;
}
// ----------------
@Configuration
// 開啟Pet的配置綁定功能, 并將Pet注入到容器中
@EnableConfigurationProperties(value = {Pet.class})
public class BeanConfig
{
}
打印結(jié)果相同