spring5 注解API 小记
# ps: 在 代码中使用了 lombox 代替get set
# ps2: 在代码中 Person 等 实体类代码被省略并未贴出
@Configuration : 把一个类作为ioc容器, 在此类中的函数上加上@Bean ,即可将对象最为Bean加入到SpringIoc中 example
@ComponentScans & @ComponentScan : 替换xml文件中 包扫描的功能, 可以指定包名称 or 类名 example
@Scope 用于指定scope作用域 (只能用在类上) example
@Lazy 延迟初始化 (只针对哪些在SpringIoc容器初始化时一起初始化的类) example
@Conditional : 按照一定的条件进行判断,满足条件给容器注册Bean example
@Import 导入外部资源 example
@Bean 生命周期 example
@Configuration
public class MyConfigTest {
/**
* 默认取 getMyConfigTest 函数名作为key
* 以@Bean("person") 设置的名称 优先
* @return
*/
@Bean()
public Person getMyConfigTest() {
return new Person();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext acalc = new AnnotationConfigApplicationContext(MyConfigTest.class);
Object getMyConfigTest = acalc.getBean("getMyConfigTest");
System.out.println(
getMyConfigTest
);
}
}
@ComponentScans({
@ComponentScan(
value = "com.js.project"
// 按照注解过滤 只要 带有 controller的注解
// ,includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})
// 按照class 过滤
// ,includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {Person.class})
// 自定义过滤
,includeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, value = {
MyTypeFilter.class})
,useDefaultFilters = false
)
})
@Configuration
public class MyComponentsScan {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyComponentsScan.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(
beanDefinitionName
);
}
}
}
class MyTypeFilter implements TypeFilter {
/**
* @param metadataReader 获取当前正在操作的类信息
* @param metadataReaderFactory 获取上下文中所有的信息
* @return
* @throws IOException
*/
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
// 获取当前类的注解信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
// 获取当前类的 class信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
if (classMetadata.getClassName().contains("My")) {
return true;
}
return false;
}
}
@Configuration
public class MyScopeTest {
/**
* prototype 原型,多例
* singleton 单例
* request web模块下 一个请求 一个实例
* session web模块下 一个会话 一个实例
*/
@Scope(value = "prototype")
@Bean("person")
public Person person() {
return new Person();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyScopeTest.class);
Object person = context.getBean("person");
Object person2 = context.getBean("person");
System.out.println(
person == person2
);
}
}
@Configuration
public class MyLazy {
@Lazy
@Bean
public Person person() {
System.out.println(
"create Person "
);
return new Person();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyLazy.class);
System.out.println(
"Ioc init "
);
Object person = context.getBean("person");
}
}
@Configuration
public class MyCondition {
/**
* Conditional 做对象控制, 在什么情况下加载对象
* 在windows 下加载 me
* @return
*/
@Conditional(WindowsConditional.class)
@Bean("me")
public Person me() {
return new Person();
}
/**
* Conditional 做对象控制, 在什么情况下加载对象
* 在linux 下加载 you
* @return
*/
@Conditional(LinuxConditional.class)
@Bean("you")
public Person you() {
return new Person();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyCondition.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(
beanDefinitionName
);
}
}
}
class WindowsConditional implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
// 获得环境变量
Environment environment = conditionContext.getEnvironment();
// 获得系统名称
String osName = environment.getProperty("os.name");
System.out.println(
osName
);
if (osName.contains("Windows")) {
return true;
}
return false;
}
}
class LinuxConditional implements Condition {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
// 获得环境变量
Environment environment = conditionContext.getEnvironment();
// 获得系统名称
String osName = environment.getProperty("os.name");
System.out.println(
osName
);
if (osName.contains("Linux")) {
return true;
}
return false;
}
}
@Configuration
/* 使用 import 导入 默认将会使用全类名 最为key */
@Import({
Person.class,
MyImportSelector.class,
MyImportDefinitionRegistrar.class})
public class MyImportTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyImportTest.class);
for (String beanDefinitionName : context.getBeanDefinitionNames()) {
System.out.println(
beanDefinitionName
);
}
}
}
class MyImportSelector implements ImportSelector {
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{
"com.js.project.repository.MyRepository","com.js.project.service.MyService"};
}
}
class MyImportDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean b = registry.containsBeanDefinition("com.js.project.repository.MyRepository");
boolean x = registry.containsBeanDefinition("com.js.project.service.MyService");
if (x && b) {
BeanDefinition rootBeanDefinition = new RootBeanDefinition(PeopleController.class);
registry.registerBeanDefinition("peopleController", rootBeanDefinition);
}
}
}
@Configuration
@Import(MyBeanPostProcessor.class)
public class MyClassLifeTest {
/**
* 1.通过 Bean 配置生命周期函数
* 2.通过 实现 InitializingBean, DisposableBean
* 3.通过注解 @PostConstruct , @PreDestroy
* 4.通过实现 BeanPostProcessor
*/
/**
* 配置生命周期
* @return
*/
@Lazy
@Bean(initMethod = "born", destroyMethod = "dead")
public Person person() {
return new Person();
}
/**
* 实现生命周期接口
* @return
*/
@Lazy
@Bean()
public People people() {
return new People();
}
/**
* 注解配置生命周期
* @return
*/
@Lazy
@Bean()
public ExtraTerrestrial extraTerrestrial() {
return new ExtraTerrestrial();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyClassLifeTest.class);
// Person person = (Person) context.getBean("person");
// person.work();
// People people = (People) context.getBean("people");
// people.work();
/* ExtraTerrestrial extraTerrestrial = (ExtraTerrestrial) context.getBean("extraTerrestrial");
extraTerrestrial.work();*/
context.close();
}
}
class ExtraTerrestrial {
public ExtraTerrestrial() {
System.out.println(" create 外星人 ");
}
public void work() {
System.out.println(" 外星人 也要工作 .....");
}
/**
* 构造之后
*/
@PostConstruct
public void bron() {
System.out.println("出生 .....");
}
/**
* 销毁之前
*/
@PreDestroy
public void dead() {
System.out.println("挂掉 ......");
}
}
class People implements InitializingBean, DisposableBean {
public void destroy() throws Exception {
System.out.println("一样挂掉 ...... ");
}
public void work() {
System.out.println(" work .......");
}
public void afterPropertiesSet() throws Exception {
System.out.println("一样出生... ");
}
}
class Person {
public Person() {
System.out.println("create person ......... ");
}
public void born() {
System.out.println("出生... ");
}
public void work() {
System.out.println("工具人+打工人 ");
}
public void dead() {
System.out.println("挂掉 ...... ");
}
}
class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName + " born ..... ");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName + " dead ..... ");
return bean;
}
}