本文章主要讲述当项目不需要某个类时,通过一个自定义注解解决,以节省内存资源.
1.随意创建一个实体类,做认证用
public class ConfigRegister {
}
2.自定义注解类
//表示该注解可用在 类,接口,枚举 等
@Target(ElementType.TYPE)
//运行时有效
@Retention(RetentionPolicy.RUNTIME)
//这里导入的是认证用的类
@Import(ConfigRegister.class)
public @interface EnableRegisterServer {
}
3-1.准备验证
@Configuration
//表示该 MyAutoConfiguration 类只有在上下文中存在了 ConfigRegister 类时,才会生效
@ConditionalOnBean(ConfigRegister.class)
public class MyAutoConfiguration {
//随意输出的一个静态代码块..启动时自动运行...
static {
System.out.println("**** MyAutoConfiguration init ....");
}
@Bean
public UserBean userBean(){
return new UserBean();
}
}
3-2.在resource中创建META-INF文件夹并创建spring.factories文件
#org.springframework.boot.autoconfigure.EnableAutoConfiguration 这里key不能动 value为绝对路径
#在springboot启动时会扫描到所有jar下的 spring.factories 文件,通过绝对路径生成到容器中
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xuxu.config.MyAutoConfiguration
3-3.创建UserBean实体类
//表示可通过用yml为该类赋值为该类赋值 -> userbean.id
@ConfigurationProperties(prefix = "userbean")
@Data
public class UserBean {
private Integer id;
private String username;
}
3-4.在yml中赋值
userbean:
id: 1
username: 吕布
4.测试
创建测试类
@Autowired
private UserBean userBean;
@Test
public void beanTest(){
System.out.println(userBean);
}
当没有在启动项上添加自定义注解(EnableRegisterServer)时…
@SpringBootApplication
public class Demo01Application {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xuxu.pojo.UserBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1799)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1355)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656)
... 76 more
当添加后…
@SpringBootApplication
//自定义注解 -> 热插拔技术
@EnableRegisterServer
public class Demo01Application {
public static void main(String[] args) {
SpringApplication.run(Demo01Application.class, args);
}
}
5.原理:
当springboot的run方法运行时,会扫描启动类上的注解,当扫描到了自定义注解->EnableRegisterServer时发现元注解@Import.并会自动在上下文中创建’认证类’->ConfigRegister
当@ConditionalOnBean判定为true时,才会创建被@ConditionalOnBean标记的类
[END]