Commit 09920e92 by 仲光辉

init at 2020/11/25 16:50 ZGH.MercyModest

parents
# Created by .ignore support plugin (hsz.mobi)
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.idea
*.iml
target
**/target
**/**/target
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<groupId>cn.dankal.share</groupId>
<artifactId>dankal-share-spring-annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<description>蛋壳创意科技-学习分享-Spring注解驱动</description>
<packaging>jar</packaging>
<dependencies>
<!--spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!--spring-test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!--hutool-core-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.4.6</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.dankal.share.beanpostprocessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* {@link BeanPostProcessor}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class BaseBeanPostProcessor implements BeanPostProcessor {
/**
* 执行 bean 的 初始化方法执行之前执行
*
* @param bean 当 bean实例对象
* @param beanName 当前 bean 在 IOC 容器中 的名称
* @return 当前 bean 实例
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BaseBeanPostProcessor ==> postProcessBeforeInitialization: " + beanName);
return bean;
}
/**
* 执行 bean 的 初始化方法执行之后执行
*
* @param bean 当 bean实例对象
* @param beanName 当前 bean 在 IOC 容器中 的名称
* @return 当前 bean 实例
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BaseBeanPostProcessor ==> postProcessAfterInitialization: " + beanName);
return bean;
}
}
package cn.dankal.share.beanpostprocessor;
import cn.dankal.share.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link BaseBeanPostProcessor}
* BeanPostProcessorConfig
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(BaseBeanPostProcessor.class)
public class BeanPostProcessorConfig {
@Bean
public Person person() {
return new Person();
}
}
package cn.dankal.share.condition;
import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* {@link Condition}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
public class RegisterBeanCondition implements Condition {
/**
* @param context ConditionContext
* @param metadata AnnotatedTypeMetadata
* @return boolean 当且仅当返回 true 条件才生效
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 获取环境对象
Environment environment = context.getEnvironment();
String testEnv = environment.getProperty("TEST_ENV");
final String matchValue = "true";
// 当环境变量: TEST_ENV 的值为 true时,当前Condition才生效
return StrUtil.equalsAnyIgnoreCase(matchValue, testEnv);
}
}
package cn.dankal.share.condition;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* {@link Configuration}
* RegisterConditionConfig
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@ComponentScan(basePackages = {"cn.dankal.share.condition"})
public class RegisterConditionConfig {
@Bean
@Conditional(RegisterBeanCondition.class)
public Study study(){
return new Study()
.setSubjectName("Spring编程思想")
.setSubjectHour(15)
.setSubjectDesc("循序渐进,熟读精思");
}
}
package cn.dankal.share.entity;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* Person
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class Person {
public Person() {
System.out.println("Construct ==> Person");
}
@PostConstruct
public void postConstruct() {
System.out.println("Person ==> postConstruct()");
}
@PreDestroy
public void preDestroy() {
System.out.println("Person ==> preDestroy()");
}
}
package cn.dankal.share.entity;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* {@link Data} {@link Accessors}
* Study
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Data
@Accessors(chain = true)
public class Study {
/**
* 学习课程
*/
private String subjectName;
/**
* 课时
*/
private Integer subjectHour;
/**
* 学习详情
*/
private String subjectDesc;
public Study() {
System.out.println("init by Study nonArgsConstruct ... ...");
}
public void init() {
System.out.println("init: --> invoke the study init method");
}
public void destroy() {
System.out.println("destroy: --> invoke the study destroy method");
}
}
package cn.dankal.share.entity;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Subject
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class Subject implements InitializingBean, DisposableBean {
public Subject() {
System.out.println("Subject ==> Construct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Subject ==> afterPropertiesSet()");
}
@Override
public void destroy() throws Exception {
System.out.println("Subject ==> destroy()");
}
}
package cn.dankal.share.factory;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link StudyFactoryBean}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(StudyFactoryBean.class)
public class FactoryBeanConfig {
}
package cn.dankal.share.factory;
import cn.dankal.share.entity.Study;
import org.springframework.beans.factory.FactoryBean;
/**
* {@link FactoryBean}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class StudyFactoryBean implements FactoryBean<Study> {
/**
* 返回 FactoryBean 生产的实例
*
* @return FactoryBean 生产的实例
* @throws Exception
*/
@Override
public Study getObject() throws Exception {
return new Study()
.setSubjectName("SpringBoot核心编程思想")
.setSubjectHour(30)
.setSubjectDesc("一入Java深似海");
}
/**
* FactoryBean 生产的实例 的 class 类型
*
* @return class type
*/
@Override
public Class<?> getObjectType() {
return Study.class;
}
/**
* 是否是单例
*
* @return boolean
*/
@Override
public boolean isSingleton() {
return true;
}
}
package cn.dankal.share.filter;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
/**
* {@link TypeFilter}
* RegisterTypeFilter
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
public class RegisterTypeFilter implements TypeFilter {
/**
* Spring 每 扫描一个 类 都会 调用 此方法.
* <br/>
* 当且仅当 此方法 返回 true 时,包含和排除 才会生效
*
* @param metadataReader MetadataReader
* @param metadataReaderFactory MetadataReaderFactory
* @return boolean
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
String className = classMetadata.getClassName();
System.out.println("className = " + className);
final String containString = "subject";
if (StrUtil.containsIgnoreCase(className, containString)) {
// 包含 类名 包含 subject 不会被排除
return false;
}
// 默认都注册
return true;
}
}
package cn.dankal.share.importbeandefinition;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link StudyRegistrar}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(StudyRegistrar.class)
public class BeanRegistrarConfig {
}
package cn.dankal.share.importbeandefinition;
import cn.dankal.share.entity.Study;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
/**
* {@link ImportBeanDefinitionRegistrar}
* StudyRegistrar
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class StudyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* register bean definitions
*
* @param importingClassMetadata AnnotationMetadata
* @param registry BeanDefinitionRegistry
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// 建议 通过 BeanDefinitionBuilder 构建 BeanDefinition 因为TA会帮对一些成员属性进行默认初数化
// 而我们直接 new 的话,则不会
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
AbstractBeanDefinition studyBeanDefinition = beanDefinitionBuilder.getBeanDefinition();
studyBeanDefinition.setBeanClass(Study.class);
registry.registerBeanDefinition("study-mercymodest", studyBeanDefinition);
// 设置作用域
//studyBeanDefinition.setScope();
// 初始化这个 bean 之前,需要先初始那些bean
//studyBeanDefinition.setDependsOn();
// 如果是单实例 bean 是否懒加载
//studyBeanDefinition.setLazyInit();
}
}
package cn.dankal.share.imports;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
/**
* {@link ImportSelector}
* CoreBeanImportSelector
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
public class CoreBeanImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// 不能返回null,会报错
//return null;
// 返回需要注册的类的全类名 数组
return new String[]{"cn.dankal.share.entity.Study","cn.dankal.share.scope.SubjectMapper"};
}
}
package cn.dankal.share.imports;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Import;
/**
* {@link Import}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Import({Study.class, CoreBeanImportSelector.class})
public class ImportRegisterBeanConfiguration {
}
package cn.dankal.share.java.annotation;
import java.lang.annotation.*;
/**
* {@link Retention} {@link Target}
* 蛋壳科技日志标识注解
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD})
public @interface DanKalTechnologyLog {
/**
* 日志前缀
*
* @since v1.0.0.0
*/
String prefix() default "cn.dankal";
/**
* 日志打印日期格式
*
* @since v1.0.0.0
*/
String dateTimePattern() default "yyyyMMdd HH:mm:ss";
/**
* 是否使用 Java8 新提供的时间 API
*
* @since v1.0.0.0
*/
boolean isUseJava8DateTime() default true;
}
package cn.dankal.share.java.annotation;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import java.lang.annotation.Annotation;
/**
* 测试 获取 对象 注解信息
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Configuration
@Scope("prototype")
@DanKalTechnologyLog(prefix = "cn.dankal.share")
public class TestGetObjectAnnotationInfo {
public static void main(String[] args) {
// 获取对应类的字节码对象
// etc TestGetObjectAnnotationInfo
Class<TestGetObjectAnnotationInfo> classObject = TestGetObjectAnnotationInfo.class;
// 获取 TestGetObjectAnnotationInfo 所有注解信息
Annotation[] annotations = classObject.getAnnotations();
for (Annotation annotation : annotations) {
// 注解类型
Class<? extends Annotation> annotationType = annotation.annotationType();
System.out.println("annotationType = " + annotationType);
// 向下转型
if (annotation instanceof DanKalTechnologyLog) {
DanKalTechnologyLog danKalTechnologyLog = (DanKalTechnologyLog) annotation;
// 获取相关注解属性值
String prefix = danKalTechnologyLog.prefix();
String dateTimePattern = danKalTechnologyLog.dateTimePattern();
boolean useJava8DateTime = danKalTechnologyLog.isUseJava8DateTime();
System.out.println("prefix = " + prefix);
System.out.println("dateTimePattern = " + dateTimePattern);
System.out.println("useJava8DateTime = " + useJava8DateTime);
}
}
}
}
package cn.dankal.share.lifecycle;
import cn.dankal.share.entity.Person;
import cn.dankal.share.entity.Study;
import cn.dankal.share.entity.Subject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* {@link}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(Person.class)
public class BeanLifecycleConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public Study study() {
return new Study()
.setSubjectName("Java并发学习")
.setSubjectHour(20)
.setSubjectDesc("Doug Lea NB!!!");
}
@Bean
public Subject subject() {
return new Subject();
}
}
package cn.dankal.share.register;
import cn.dankal.share.entity.Study;
import cn.dankal.share.filter.RegisterTypeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
/**
* {@link Configuration} {@link Bean}
* RegisterBean
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Configuration
@ComponentScan(basePackages = {"cn.dankal.share.service"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {RegisterTypeFilter.class})
})
public class RegisterBean {
@Bean
public Study study() {
return new Study()
.setSubjectName("Mybatis源码小析")
.setSubjectHour(15)
.setSubjectDesc("那些年我为啥嫌弃JDBC");
}
}
package cn.dankal.share.register;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* {@link Configuration}
* RegisterBeanWithScope
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@ComponentScan(basePackages = {"cn.dankal.share.scope"})
public class RegisterBeanWithScope {
}
package cn.dankal.share.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* {@link StudyMapper}
* StudyMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Scope(scopeName = "prototype")
@Repository
public class StudyMapper {
public StudyMapper() {
System.out.println("StudyMapper init by Construct");
}
public void init() {
System.out.println("初始化 --> StudyMapper");
}
public void destroy() {
System.out.println("销毁 --> StudyMapper");
}
}
package cn.dankal.share.scope;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
/**
* {@link Repository}
* SubjectMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Lazy
@Repository
public class SubjectMapper {
public SubjectMapper() {
System.out.println("SubjectMapper init by Construct");
}
}
package cn.dankal.share.service;
/**
*
* StudyService
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
public interface StudyService {
}
package cn.dankal.share.service;
/**
* SubjectService
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
public interface SubjectService {
}
package cn.dankal.share.service.impl;
import cn.dankal.share.service.StudyService;
import org.springframework.stereotype.Service;
/**
* {@link Service}
* StudyServiceImpl
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Service
public class StudyServiceImpl implements StudyService {
}
package cn.dankal.share.service.impl;
import cn.dankal.share.service.SubjectService;
import org.springframework.stereotype.Service;
/**
* {@link Service} {@link SubjectService}
* SubjectServiceImpl
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Service
public class SubjectServiceImpl implements SubjectService {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:content="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注册一个多实例学习bean-->
<bean id="study" class="cn.dankal.share.entity.Study" scope="prototype" lazy-init="true">
<property name="subjectName" value="Spring源码小析"/>
<property name="subjectHour" value="12"/>
<property name="subjectDesc" value="学习Spring源码的小艺术"/>
</bean>
<!--spring 包扫描-->
<content:component-scan base-package="cn.dankal.share.service" use-default-filters="false">
<content:include-filter type="assignable" expression="cn.dankal.share.service.SubjectService"/>
</content:component-scan>
<!--注册一个Bean 并指定 初始化方法和销毁方法-->
<bean id="studyMapper" class="cn.dankal.share.scope.StudyMapper" init-method="init" destroy-method="destroy"/>
</beans>
\ No newline at end of file
package cn.dankal.share.test;
import cn.dankal.share.beanpostprocessor.BeanPostProcessorConfig;
import cn.dankal.share.condition.RegisterConditionConfig;
import cn.dankal.share.factory.FactoryBeanConfig;
import cn.dankal.share.importbeandefinition.BeanRegistrarConfig;
import cn.dankal.share.imports.ImportRegisterBeanConfiguration;
import cn.dankal.share.lifecycle.BeanLifecycleConfig;
import cn.dankal.share.register.RegisterBean;
import cn.dankal.share.register.RegisterBeanWithScope;
import cn.dankal.share.scope.StudyMapper;
import cn.dankal.share.scope.SubjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
/**
* {@link ContextConfiguration} {@link RunWith} {@link SpringJUnit4ClassRunner}
* SpringIocMainTest
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-application.xml"})
public class SpringIocMainTest {
/**
* the applicationContext by xml class path config file
*/
@Autowired
private ApplicationContext applicationContext;
/**
* 基于 XML
*/
@Test
public void testIocBeanDefinitionListByXml() {
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
/**
* 基于配置类 (注解)
*/
@Test
public void testIocBeanDefinitionListByConfiguration() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterBean.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
/**
* 测试 Spring Bean 的作用域
*/
@Test
public void testIocBeanWithScope() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterBeanWithScope.class);
System.out.println("=============== StudyMapper ===============");
System.out.println(applicationContext.getBeansOfType(StudyMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(StudyMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(StudyMapper.class).toString());
System.out.println("=============== SubjectMapper ===============");
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
}
/**
* Spring 单实例 Bean 的懒加载
*/
@Test
public void testSingletonBeanLazy() {
// 创建 Spring IOC 容器对象. 即完成Spring IOC 容器的初始化
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterBeanWithScope.class);
System.out.println("the applicationContext is finished initialize");
System.out.println("=============== SubjectMapper ===============");
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
}
/**
* Spring 条件注册
*/
@Test
public void testRegisterBeanByCondition() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterConditionConfig.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
/**
* @code @Import 注册一个类
*/
@Test
public void testImportRegisterBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ImportRegisterBeanConfiguration.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
/**
* @code @Import + ImportSelector
*/
@Test
public void testImportBeanDefinitionRegistrar() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanRegistrarConfig.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
/**
* FactoryBean 注册一个 对象
*/
@Test
public void testFactoryBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(FactoryBeanConfig.class);
// FactoryBean 生产 的Bean
String beanName = "cn.dankal.share.factory.StudyFactoryBean";
System.out.println("FactoryBean 生产 的Bean: \t" + applicationContext.getBean(beanName).getClass().getName());
// FactoryBean 本身
String realBeanName = "&cn.dankal.share.factory.StudyFactoryBean";
System.out.println("FactoryBean 本身: \t" + applicationContext.getBean(realBeanName).getClass().getName());
}
/**
* Spring Bean 的生命周期
*/
@Test
public void testBeanLifecycle() {
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifecycleConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
/**
* @code BeanPostProcessor 后置处理器
*/
@Test
public void testBeanPostProcessor() {
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanPostProcessorConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
}
# 关于Spring注解驱动开发的小分享
# 关于Spring注解驱动开发的小分享
## Java注解
### 定义:
> Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。
>
> Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。
### JDK 内置三个基本注解
> - **@Override**
>
> > 限定某个方法是重写父类/接口的方法
>
> - **@Deprecated**
>
> > 用于表示某个程序元素已经过时
>
> - **@SuppressWarnings**
>
> > 用于一直编译器警告
### JDK 元注解
> - **@Retention**
>
> - 声明注解的生命周期
> - SOURCE :Annotations are to be discarded by the compiler.
> - CLASS : Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.
> - RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
>
> - **@Documented**
>
> - 注解是否会在 JavaDoc 中提现
>
> - **@Target**
>
> - 注解可以在哪些地方使用
>
> - TYPE
> - FIELD
> - METHOD
> - PARAMETER
> - CONSTRUCTOR
> - LOCAL_VARIABLE
> - ANNOTATION_TYPE
> - PACKAGE
>
> -
> - TYPE_PARAMETER
> - TYPE_USE
>
> - **@Inherited**
> - 注解是否会被继承
### 自定义Java注解
DanKalTechnologyLog.java
```java
package cn.dankal.share.java.annotation;
import java.lang.annotation.*;
/**
* {@link Retention} {@link Target}
* 蛋壳科技日志标识注解
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD})
public @interface DanKalTechnologyLog {
/**
* 日志前缀
*
* @since v1.0.0.0
*/
String prefix() default "cn.dankal";
/**
* 日志打印日期格式
*
* @since v1.0.0.0
*/
String dateTimePattern() default "yyyyMMdd HH:mm:ss";
/**
* 是否使用 Java8 新提供的时间 API
*
* @since v1.0.0.0
*/
boolean isUseJava8DateTime() default true;
}
```
通过 JDK 反射 获取注解信息以实现相关功能
```java
package cn.dankal.share.java.annotation;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import java.lang.annotation.Annotation;
/**
* 测试 获取 对象 注解信息
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Configuration
@Scope("prototype")
@DanKalTechnologyLog(prefix = "cn.dankal.share")
public class TestGetObjectAnnotationInfo {
public static void main(String[] args) {
// 获取对应类的字节码对象
// etc TestGetObjectAnnotationInfo
Class<TestGetObjectAnnotationInfo> classObject = TestGetObjectAnnotationInfo.class;
// 获取 TestGetObjectAnnotationInfo 所有注解信息
Annotation[] annotations = classObject.getAnnotations();
for (Annotation annotation : annotations) {
// 注解类型
Class<? extends Annotation> annotationType = annotation.annotationType();
System.out.println("annotationType = " + annotationType);
// 向下转型
if (annotation instanceof DanKalTechnologyLog) {
DanKalTechnologyLog danKalTechnologyLog = (DanKalTechnologyLog) annotation;
// 获取相关注解属性值
String prefix = danKalTechnologyLog.prefix();
String dateTimePattern = danKalTechnologyLog.dateTimePattern();
boolean useJava8DateTime = danKalTechnologyLog.isUseJava8DateTime();
System.out.println("prefix = " + prefix);
System.out.println("dateTimePattern = " + dateTimePattern);
System.out.println("useJava8DateTime = " + useJava8DateTime);
}
}
}
}
```
## Spring注解
因为Spring注解还是相对比较庞大的,所以呢我就SpringIOC容器相关的常用注解已经一些简单的拓展和大家展开交流
### 向SpringIOC容器在注册一个Bean
#### 基于XML
```xml
<!--注册一个学习bean-->
<bean id="study" class="cn.dankal.share.entity.Study">
<property name="subjectName" value="Spring源码小析"/>
<property name="subjectHour" value="12"/>
<property name="subjectDesc" value="学习Spring源码的小艺术"/>
</bean>
```
#### 基于注解
```java
package cn.dankal.share.register;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* {@link Configuration} {@link Bean}
* RegisterBean
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Configuration
public class RegisterBean {
@Bean
public Study study() {
return new Study()
.setSubjectName("Mybatis源码小析")
.setSubjectHour(15)
.setSubjectDesc("那些年我为啥嫌弃JDBC");
}
}
```
> @Configuration —> 一个Spring 配置文件 etc. spring-applciation.xml
>
> @Bean – > Spring配置文件中否 bean 节点(xml)
### 向SpringIOC中批量注册bean
#### 基于XML
cn.dankal.share.service 下面带有
- @Service
- @Controller
- @Component
- @Repository
- @Configuration
注解 的 类会被Spring以Spring bean 的形式实例化并放到 SpringIOC 容器中
```xml
<!--spring 包扫描-->
<content:component-scan base-package="cn.dankal.share.service"/>
```
结果测试
```java
package cn.dankal.share.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
/**
* {@link ContextConfiguration} {@link RunWith} {@link SpringJUnit4ClassRunner}
* SpringIocMainTest
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@ContextConfiguration(locations = {"classpath:spring-application.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringIocMainTest {
/**
* the applicationContext by xml class path config file
*/
@Autowired
private ApplicationContext applicationContext;
@Test
public void testIocBeanDefinitionListByXml() {
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
}
```
![](https://img.mercymodest.com/public/20201123180502.png)
#### 基于配置类(注解)
```java
package cn.dankal.share.register;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* {@link Configuration} {@link Bean}
* RegisterBean
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Configuration
@ComponentScan(basePackages = {"cn.dankal.share.service"})
public class RegisterBean {
... other config ...
}
```
结果测试
```java
@Test
public void testIocBeanDefinitionListByConfiguration() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterBean.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
```
![](https://img.mercymodest.com/public/20201123180809.png)
### Spring 扫描过滤
#### 过滤类型
> - 扫描包含
> - 扫描排除
#### 过滤方式
```java
package org.springframework.context.annotation;
/**
* Enumeration of the type filters that may be used in conjunction with
* {@link ComponentScan @ComponentScan}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @since 2.5
* @see ComponentScan
* @see ComponentScan#includeFilters()
* @see ComponentScan#excludeFilters()
* @see org.springframework.core.type.filter.TypeFilter
*/
public enum FilterType {
/**
* Filter candidates marked with a given annotation.
* @see org.springframework.core.type.filter.AnnotationTypeFilter
*/
ANNOTATION,
/**
* Filter candidates assignable to a given type.
* @see org.springframework.core.type.filter.AssignableTypeFilter
*/
ASSIGNABLE_TYPE,
/**
* Filter candidates matching a given AspectJ type pattern expression.
* @see org.springframework.core.type.filter.AspectJTypeFilter
*/
ASPECTJ,
/**
* Filter candidates matching a given regex pattern.
* @see org.springframework.core.type.filter.RegexPatternTypeFilter
*/
REGEX,
/** Filter candidates using a given custom
* {@link org.springframework.core.type.filter.TypeFilter} implementation.
*/
CUSTOM
}
```
#### 扫描包含
##### 基于XML
小提示:需要关闭 Spring 默认过来规则,否则 include-filter 无法生效
` use-default-filters="false"`
```xml
<!--spring 包扫描-->
<content:component-scan base-package="cn.dankal.share.service" use-default-filters="false">
<content:include-filter type="assignable" expression="cn.dankal.share.service.SubjectService"/>
</content:component-scan>
```
###### 过滤前
![](https://img.mercymodest.com/public/20201123181659.png)
###### 过滤后
![](https://img.mercymodest.com/public/20201123181738.png)
#### 扫描排除
##### 基于配置类(注解)
```java
package cn.dankal.share.register;
import cn.dankal.share.entity.Study;
import cn.dankal.share.service.StudyService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(basePackages = {"cn.dankal.share.service"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {StudyService.class})
})
public class RegisterBean {
... other condfig ...
}
```
###### 过滤前
![](https://img.mercymodest.com/public/20201123182126.png)
###### 过滤后
![](https://img.mercymodest.com/public/20201123182040.png)
##### 通过 TypeFilter 实现过滤
RegisterTypeFilter.java
```java
package cn.dankal.share.filter;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
/**
* {@link TypeFilter}
* RegisterTypeFilter
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
public class RegisterTypeFilter implements TypeFilter {
/**
* Spring 每 扫描一个 类 都会 调用 此方法.
* <br/>
* 当且仅当 此方法 返回 true 时,被扫描的 类才会以 SpringBean 的形式注册
*
* @param metadataReader MetadataReader
* @param metadataReaderFactory MetadataReaderFactory
* @return boolean
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
String className = classMetadata.getClassName();
System.out.println("className = " + className);
final String containString = "subject";
if (StrUtil.containsIgnoreCase(className, containString)) {
// 包含 类名 包含 subject 不会被排除
return false;
}
// 默认都注册
return true;
}
}
```
配置使用
```java
package cn.dankal.share.register;
import cn.dankal.share.entity.Study;
import cn.dankal.share.filter.RegisterTypeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(basePackages = {"cn.dankal.share.service"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {RegisterTypeFilter.class})
})
public class RegisterBean {
@Bean
public Study study() {
return new Study()
.setSubjectName("Mybatis源码小析")
.setSubjectHour(15)
.setSubjectDesc("那些年我为啥嫌弃JDBC");
}
}
```
###### 过滤前
![](https://img.mercymodest.com/public/20201123183702.png)
###### 过滤后
![](https://img.mercymodest.com/public/20201123183830.png)
### Spring Bean 作用域
```java
// @Scope
/**
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
* @see #value
*/
@AliasFor("value")
String scopeName() default "";
```
> - singleton (默认),单例
> - prototype
> - request
> - session
#### 基于XML 指定 bean 的作用域
![](https://img.mercymodest.com/public/20201124094208.png)
```xml
<!--注册一个多实例学习bean-->
<bean id="study" class="cn.dankal.share.entity.Study" scope="prototype">
<property name="subjectName" value="Spring源码小析"/>
<property name="subjectHour" value="12"/>
<property name="subjectDesc" value="学习Spring源码的小艺术"/>
</bean>
```
#### 基于注解`@Scope`
StudyMapper.java
```java
package cn.dankal.share.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* {@link StudyMapper}
* StudyMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Scope(scopeName = "prototype")
@Repository
public class StudyMapper {
}
```
SubjectMapper.java
```java
package cn.dankal.share.scope;
import org.springframework.stereotype.Repository;
/**
* {@link Repository}
* SubjectMapper
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Repository
public class SubjectMapper {
}
```
测试结果
![](https://img.mercymodest.com/public/20201124094937.png)
#### 小提示
> 在 Spring IOC 容器中,单实例Bean (singleton)是在 随着 IOC 容器的初始化而初始化,随着IOC 容器的销毁而销毁.而多实例Bean(prototype)在我们每次获取的时候进行新的创建(初始化).
### @Lazy:单实例Bean 的懒加载
SubjectMapper.java
```java
package cn.dankal.share.scope;
import org.springframework.stereotype.Repository;
/**
* {@link Repository}
* SubjectMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Repository
public class SubjectMapper {
public SubjectMapper() {
System.out.println("SubjectMapper init by Construct");
}
}
```
单元测试
```java
@Test
public void testSingletonBeanLazy() {
// 创建 Spring IOC 容器对象. 即完成Spring IOC 容器的初始化
new AnnotationConfigApplicationContext(RegisterBeanWithScope.class);
System.out.println("the applicationContext is finished initialize");
}
```
运行结果
![](https://img.mercymodest.com/public/20201124095937.png)
#### 使用@Lazy
SubjectMapper.java
```java
package cn.dankal.share.scope;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
/**
* {@link Repository}
* SubjectMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Lazy
@Repository
public class SubjectMapper {
public SubjectMapper() {
System.out.println("SubjectMapper init by Construct");
}
}
```
测试结果
![](https://img.mercymodest.com/public/20201124100157.png)
当我获取 SubjectMapper Bean 实例时
```java
@Test
public void testSingletonBeanLazy() {
// 创建 Spring IOC 容器对象. 即完成Spring IOC 容器的初始化
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterBeanWithScope.class);
System.out.println("the applicationContext is finished initialize");
System.out.println("=============== SubjectMapper ===============");
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
System.out.println(applicationContext.getBeansOfType(SubjectMapper.class).toString());
}
```
测试结果
![](https://img.mercymodest.com/public/20201124100551.png)
#### 使用 XML
```xml
<!--注册一个多实例学习bean-->
<bean id="study" class="cn.dankal.share.entity.Study" scope="prototype" lazy-init="true">
<property name="subjectName" value="Spring源码小析"/>
<property name="subjectHour" value="12"/>
<property name="subjectDesc" value="学习Spring源码的小艺术"/>
</bean>
```
![](https://img.mercymodest.com/public/20201124101155.png)
### SpringBean 的条件注册
> 1. 实现 Condition接口
>
> 2. 使用@Condition 注解
>
> ```java
> @Target({ElementType.TYPE, ElementType.METHOD})
> @Retention(RetentionPolicy.RUNTIME)
> @Documented
> public @interface Conditional {
>
> /**
> * All {@link Condition}s that must {@linkplain Condition#matches match}
> * in order for the component to be registered.
> */
> Class<? extends Condition>[] value();
>
> }
> ```
#### RegisterBeanCondition.java
```java
package cn.dankal.share.condition;
import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* {@link Condition}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
public class RegisterBeanCondition implements Condition {
/**
* @param context ConditionContext
* @param metadata AnnotatedTypeMetadata
* @return boolean 当且仅当返回 true 条件才生效
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// 获取环境对象
Environment environment = context.getEnvironment();
String testEnv = environment.getProperty("TEST_ENV");
final String matchValue = "true";
// 当环境变量: TEST_ENV 的值为 true时,当前Condition才生效
return StrUtil.equalsAnyIgnoreCase(matchValue, testEnv);
}
}
```
#### configuration
```java
package cn.dankal.share.condition;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* {@link Configuration}
* RegisterConditionConfig
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@ComponentScan(basePackages = {"cn.dankal.share.condition"})
public class RegisterConditionConfig {
@Bean
@Conditional(RegisterBeanCondition.class)
public Study study(){
return new Study()
.setSubjectName("Spring编程思想")
.setSubjectHour(15)
.setSubjectDesc("循序渐进,熟读精思");
}
}
```
单元测试
```java
@Test
public void testRegisterBeanByCondition() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RegisterConditionConfig.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
```
不设置 TEST_ENV 进行测试
![](https://img.mercymodest.com/public/20201124103304.png)
使用IDEA 设置环境变量
![](https://img.mercymodest.com/public/20201124103349.png)
![](https://img.mercymodest.com/public/20201124103521.png)
#### 测试结果
![](https://img.mercymodest.com/public/20201124103551.png)
##### 小提示
> @Condition 注解的作用范围
>
> ![](https://img.mercymodest.com/public/20201124103746.png)
>
> 当我们在类上(TYPE)使用时,当且仅当 Condition 条件生效 整个 类(配置类才会生效)
>
> 当我在方法上(METHIOD)使用时, 当且仅当 Condition 条件生效 ,配置方法才会生效
### @Import :向容器中快速导入一个组件
#### 直接导入一个类
ImportRegisterBeanConfiguration.java
```java
package cn.dankal.share.imports;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Import;
/**
* {@link Import}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @reate 2020/11/24
*/
@Import({Study.class})
public class ImportRegisterBeanConfiguration {
}
```
单元测试
```java
@Test
public void testImportRegisterBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ImportRegisterBeanConfiguration.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
```
测试结果
![](https://img.mercymodest.com/public/20201124104643.png)
#### ImportSelector 批量注册
CoreBeanImportSelector.java
```java
package cn.dankal.share.imports;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
/**
* {@link ImportSelector}
* CoreBeanImportSelector
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
public class CoreBeanImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// 不能返回null,会报错
//return null;
// 返回需要注册的类的全类名 数组
return new String[]{"cn.dankal.share.entity.Study","cn.dankal.share.scope.SubjectMapper"};
}
}
```
```
package cn.dankal.share.imports;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Import;
/**
* {@link Import}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Import({Study.class, CoreBeanImportSelector.class})
public class ImportRegisterBeanConfiguration {
}
```
测试代码
```java
@Test
public void testImportRegisterBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ImportRegisterBeanConfiguration.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
```
运行结果
![](https://img.mercymodest.com/public/20201125143039.png)
##### 小提示
为什么 实现 ImportSelector 接口的时候返回null 会抛出空指针异常呢?
![](https://img.mercymodest.com/public/20201125143136.png)
#### ImportBeanDefinaitionRegister 注册一个 BeanDefinition
StudyRegistrar.java
```java
package cn.dankal.share.importbeandefinition;
import cn.dankal.share.entity.Study;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
/**
* {@link ImportBeanDefinitionRegistrar}
* StudyRegistrar
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class StudyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* register bean definitions
*
* @param importingClassMetadata AnnotationMetadata
* @param registry BeanDefinitionRegistry
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// 建议 通过 BeanDefinitionBuilder 构建 BeanDefinition 因为TA会帮对一些成员属性进行默认初数化
// 而我们直接 new 的话,则不会
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
AbstractBeanDefinition studyBeanDefinition = beanDefinitionBuilder.getBeanDefinition();
studyBeanDefinition.setBeanClass(Study.class);
registry.registerBeanDefinition("study-mercymodest", studyBeanDefinition);
// 设置作用域
//studyBeanDefinition.setScope();
// 初始化这个 bean 之前,需要先初始那些bean
//studyBeanDefinition.setDependsOn();
// 如果是单实例 bean 是否懒加载
//studyBeanDefinition.setLazyInit();
}
}
```
BeanRegistrarConfig.java
```java
package cn.dankal.share.importbeandefinition;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link StudyRegistrar}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(StudyRegistrar.class)
public class BeanRegistrarConfig {
}
```
测试代码
```java
@Test
public void testImportBeanDefinitionRegistrar() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanRegistrarConfig.class);
Arrays.stream(applicationContext.getBeanDefinitionNames())
.filter(beanName -> !beanName.contains("org.springframework"))
.forEach(System.out::println);
}
```
运行结果
![](https://img.mercymodest.com/public/20201125150755.png)
##### 小说明
> @Scope : Bean 的作用域
>
> @DependsOn: 当前 Bean 需要依赖的Bean
>
> @Lazy : 单实例 bean 的 懒加载
>
> @Primary : 说来话长 … …
>
> 先来看看官方注释:
>
> > Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
> >
> > (表示当多个候选者有资格自动装配一个单值依赖关系时,应优先考虑某个bean。如果候选者中只存在一个 "主要 "Bean,那么它将成为自动装配的值。)
> >
> > This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.
> >
> > (这个注解在语义上等同于Spring XML中<bean>元素的primary属性。)
>
> ![](https://img.mercymodest.com/public/20201125164316.png)
>
> ![](https://img.mercymodest.com/public/20201125164454.png)
### 使用 FactoryBean 注册 一个 Bean
StudyFactoryBean.java
```java
package cn.dankal.share.factory;
import cn.dankal.share.entity.Study;
import org.springframework.beans.factory.FactoryBean;
/**
* {@link FactoryBean}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class StudyFactoryBean implements FactoryBean<Study> {
/**
* 返回 FactoryBean 生产的实例
*
* @return FactoryBean 生产的实例
* @throws Exception
*/
@Override
public Study getObject() throws Exception {
return new Study()
.setSubjectName("SpringBoot核心编程思想")
.setSubjectHour(30)
.setSubjectDesc("一入Java深似海");
}
/**
* FactoryBean 生产的实例 的 class 类型
*
* @return class type
*/
@Override
public Class<?> getObjectType() {
return Study.class;
}
/**
* 是否是单例
*
* @return boolean
*/
@Override
public boolean isSingleton() {
return true;
}
}
```
FactoryBeanConfig.java
```java
package cn.dankal.share.factory;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link StudyFactoryBean}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(StudyFactoryBean.class)
public class FactoryBeanConfig {
}
```
测试
```java
@Test
public void testFactoryBean() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(FactoryBeanConfig.class);
// FactoryBean 生产 的Bean
String beanName = "cn.dankal.share.factory.StudyFactoryBean";
System.out.println("FactoryBean 生产 的Bean: \t"+applicationContext.getBean(beanName).getClass().getName());
// FactoryBean 本身
String realBeanName="&cn.dankal.share.factory.StudyFactoryBean";
System.out.println("FactoryBean 本身: \t"+applicationContext.getBean(realBeanName).getClass().getName());
}
```
运行结果
![](https://img.mercymodest.com/public/20201125151920.png)
### Spring Bean 生命周期管理
#### 基于XML
StudyMapper.java
```java
package cn.dankal.share.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* {@link StudyMapper}
* StudyMapper
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/24
*/
@Scope(scopeName = "prototype")
@Repository
public class StudyMapper {
public StudyMapper() {
System.out.println("StudyMapper init by Construct");
}
public void init() {
System.out.println("初始化 --> StudyMapper");
}
public void destroy() {
System.out.println("销毁 --> StudyMapper");
}
}
```
```xml
<!--注册一个Bean 并指定 初始化方法和销毁方法-->
<bean id="studyMapper" class="cn.dankal.share.scope.StudyMapper" init-method="init" destroy-method="destroy"/>
```
#### 基于注解
##### @Bean 注解属性
Study.java
```java
package cn.dankal.share.entity;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* {@link Data} {@link Accessors}
* Study
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/23
*/
@Data
@Accessors(chain = true)
public class Study {
/**
* 学习课程
*/
private String subjectName;
/**
* 课时
*/
private Integer subjectHour;
/**
* 学习详情
*/
private String subjectDesc;
public Study() {
System.out.println("init by Study nonArgsConstruct ... ...");
}
public void init() {
System.out.println("init: --> invoke the study init method");
}
public void destroy() {
System.out.println("destroy: --> invoke the study destroy method");
}
}
```
BeanLifecycleConfig.java
```java
package cn.dankal.share.lifecycle;
import cn.dankal.share.entity.Study;
import org.springframework.context.annotation.Bean;
/**
* {@link}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class BeanLifecycleConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public Study study() {
return new Study()
.setSubjectName("Java并发学习")
.setSubjectHour(20)
.setSubjectDesc("Doug Lea NB!!!");
}
}
```
测试方法
```java
@Test
public void testBeanLifecycle() {
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifecycleConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
```
运行结果
![](https://img.mercymodest.com/public/20201125154138.png)
##### 实现接口:InitializingBean DisposableBean
Subject.java
```java
package cn.dankal.share.entity;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Subject
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class Subject implements InitializingBean, DisposableBean {
public Subject() {
System.out.println("Subject ==> Construct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Subject ==> afterPropertiesSet()");
}
@Override
public void destroy() throws Exception {
System.out.println("Subject ==> destroy()");
}
}
```
配置
```java
package cn.dankal.share.lifecycle;
import cn.dankal.share.entity.Study;
import cn.dankal.share.entity.Subject;
import org.springframework.context.annotation.Bean;
/**
* {@link}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class BeanLifecycleConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public Study study() {
return new Study()
.setSubjectName("Java并发学习")
.setSubjectHour(20)
.setSubjectDesc("Doug Lea NB!!!");
}
// see that
@Bean
public Subject subject() {
return new Subject();
}
}
```
测试方法
```java
@Test
public void testBeanLifecycle() {
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifecycleConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
```
运行结果
![](https://img.mercymodest.com/public/20201125155038.png)
##### JSR 250 : @PostConstruct @PreDestroy
Person.java
```java
package cn.dankal.share.entity;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* Person
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class Person {
public Person() {
System.out.println("Construct ==> Person");
}
@PostConstruct
public void postConstruct() {
System.out.println("Person ==> postConstruct()");
}
@PreDestroy
public void preDestroy() {
System.out.println("Person ==> preDestroy()");
}
}
```
测试代码
```java
@Test
public void testBeanLifecycle() {
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifecycleConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
```
运行结果
![](https://img.mercymodest.com/public/20201125155756.png)
##### Bean 的后置处理器: BeanPostProcessor
BaseBeanPostProcessor.java
```java
package cn.dankal.share.beanpostprocessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* {@link BeanPostProcessor}
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
public class BaseBeanPostProcessor implements BeanPostProcessor {
/**
* 执行 bean 的 初始化方法执行之前执行
*
* @param bean 当 bean实例对象
* @param beanName 当前 bean 在 IOC 容器中 的名称
* @return 当前 bean 实例
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BaseBeanPostProcessor ==> postProcessBeforeInitialization: " + beanName);
return bean;
}
/**
* 执行 bean 的 初始化方法执行之后执行
*
* @param bean 当 bean实例对象
* @param beanName 当前 bean 在 IOC 容器中 的名称
* @return 当前 bean 实例
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BaseBeanPostProcessor ==> postProcessAfterInitialization: " + beanName);
return bean;
}
}
```
配置类
```java
package cn.dankal.share.beanpostprocessor;
import cn.dankal.share.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
/**
* {@link Import} {@link BaseBeanPostProcessor}
* BeanPostProcessorConfig
*
* @author ZGH.MercyModest
* @version V1.0.0
* @create 2020/11/25
*/
@Import(BaseBeanPostProcessor.class)
public class BeanPostProcessorConfig {
@Bean
public Person person() {
return new Person();
}
}
```
测试方法
```java
@Test
public void testBeanPostProcessor(){
// 容器初始化
ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanPostProcessorConfig.class);
System.out.println("\nthis is java program\n");
// 容器销毁
applicationContext.close();
}
```
运行结果
![](https://img.mercymodest.com/public/20201125161016.png)
###### BeanPostProcessor 典型的使用场景
AutowiredAnnotationBeanPostProcessor
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
一般我们需要从SpringIOC 容器中获取 Bean 实例时,我们通常会使用 @Autowired 注解,那么@Autowired 注解的功能实现就是通过 AutowiredAnnotationBeanPostProcessor 来实现的
> AutowiredAnnotationBeanPostProcessor
>
> ​ — extends InstantiationAwareBeanPostProcessorAdapter
>
> ​ –– implments SmartInstantiationAwareBeanPostProcessor
>
> ​ — extends InstantiationAwareBeanPostProcessor
>
> ​ — extends BeanPostProcessor
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment