
1、@Configuration 注解@Configuration告诉SpringBoot这是一个配置类 等同于 Spring5的Bean配置文件。
1)、proxyBeanMethods:代理bean的方法。
- `Full(proxyBeanMethods = true)`:【保证每个`@Bean`方法被调用多少次返回的组件都是单实例的】。- `Lite(proxyBeanMethods = false)`:【每个`@Bean`方法被调用多少次返回的组件都是新创建的】。
2)、组件依赖必须使用 Full 模式默认。其他默认是否Lite模式。
- **Full模式与Lite模式**
- 配置 类组件之间**无依赖关系**用Lite模式**加速容器启动过程,减少判断**。
- 配置类组件之间**有依赖关系**,方法会**被调用得到之前单实例组件**,用Full模式。
2、@ComponentScan 注解
@ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里。会被自动装配的注解包括@Controller、@Service、@Component、@Repository等等。其作用等同于<context:component-scan base-package="com.maple.learn" />配置
常用属性如下:
1、basePackages、value:指定扫描路径,如果为空则以 @ComponentScan 注解的类所在的包为基本的扫描路径。
单个:@ComponentScan(basePackages = “xxx”)
多个:@ComponentScan(basePackages = {“xxx”,“aaa”,“…”})
2、basePackageClasses:指定具体扫描的类
单个:@ComponentScan(basePackageClasses = “”)
多个:@ComponentScan(basePackageClasses = {“xxx”,“aaa”,“…”})
3、includeFilters:指定满足Filter条件的类
4、excludeFilters:指定排除Filter条件的类includeFilters 和 excludeFilters 的Filter Type 可选:ANNOTATION=注解类型 默认、ASSIGNABLE_TYP``E``(指定固定类)、ASPECTJ(ASPECTJ类型)、REGEX(正则表达式)、CUSTOM(自定义类型),自定义的 Filter 需要实现 TypeFilter 接口
(1)Person2类:
package com.wzy.bean.quanzhujie;
import org.springframework.stereotype.Component;
@Component(value = "person2")
public class Person2 {
private String name;
private String gender;
private Integer age;
//全参、无参、get、set方法
}
(2)创建配置类,替代 xml 配置文件
package com.wzy.bean.quanzhujie;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.wzy.bean.quanzhujie"})
public class SpringConfig {
}
(3)编写测试类
package com.wzy.bean.quanzhujie;
import javafx.application.Application;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.junit.Assert.*;
public class SpringConfigTest {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(SpringConfig.class);
@Test
public void test1(){
Person2 person2 = applicationContext.getBean("person2", Person2.class);
System.out.println(person2);
}
}
