深度解析互联网大厂面试难题自定义@EnableXX系列
深度解析互联网大厂面试难题自定义@EnableXX系列
其实是一个@Import的设计技巧
创建注解@EnableXX(任何名称注解都行,只是这个名字好一些)
XXConfiguration类不能使用@Component,不然Bean就立即注册了,达不到开关的目的
使用@EnableXX注解的时候,一定是与@Component或者@Configuration进行复合使用,否则开关本身无效,换句话说就是让别的@Component或者@Configuration把自己的@Bean带进去。
实体类
package com.example.demo14.entity;
public class Stu {
String name;
public Stu(String name) {
this.name = name;
}
public Stu() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Stu{" +
"name='" + name + '\'' +
'}';
}
}
配置类
package com.example.demo14.configuration;
import com.example.demo14.entity.Stu;
import org.springframework.context.annotation.Bean;
//注意这里,没有添加@Configuration,不然开关就失效了
public class StuConfiguration {
@Bean
public Stu stu() {
return new Stu();
}
}
注解类
package com.example.demo14.annotation;
import com.example.demo14.configuration.StuConfiguration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//这里的@Import成为了开关的关键,携带具有@Bean的类
//注意这里如果@Import是普通类,也注册的进去
@Import(StuConfiguration.class)
public @interface EnableStu {
}
启动类
package com.example.demo14;
import com.example.demo14.annotation.EnableStu;
import com.example.demo14.configuration.StuConfiguration;
import com.example.demo14.entity.Stu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Map;
@SpringBootApplication
//开启功能,然后注册Bean
//因为@SpringBootApplication本身复合了@Configuration,因此具备注册@Bean的能力
@EnableStu
public class Demo14Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo14Application.class, args);
//查看@Bean情况
Map<String, Stu> beansOfType = context.getBeansOfType(Stu.class);
System.out.println(beansOfType.size());
//查看@Configuration情况,也就是StuConfiguration自己
Map<String, StuConfiguration> beansOfType2 = context.getBeansOfType(StuConfiguration.class);
System.out.println(beansOfType2.size());
context.close();
}
}
最新文章
- go get安装第三方包的前提条件和步骤
- SQL Server判断语句(IF ELSE/CASE WHEN )
- git --如何撤销已放入缓存区(Index区)的修改
- 修复AWS上EC2损坏的sshd_config文件
- not use jquery
- Jquery 中toggle的用法举例
- Ubuntu下Sublime Text 3无法输入中文的解决方案
- mysql 参数:[read_buffer_size] [sort_buffer_size] [read_rnd_buffer_size] [tmp_table_size]---图解
- WinForm程序的发布
- SpringMVC(五):@RequestMapping下使用@RequestParam绑定请求参数值
- MySQL性能调优——锁定机制与锁优化分析
- 为什么 npm 要为每个项目单独安装一遍 node_modules?
- Docker学习笔记-Docker for Windows 安装
- 005 Numpy的基本操作
- motor的使用
- jQuery中的end()方法
- MVC仓储执行存储过程报错“未提供该参数”
- 论文笔记(3)-Extracting and Composing Robust Features with Denoising Autoencoders
- 转	 Linux会话浅析(写得极好,表述清楚语言不硬)
- Python爬虫(七)