- 使用@Import注解,给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
| @Import({User.class, DBHelper.class}) |
| @Configuration(proxyBeanMethods = false) |
| public class MyConfig { |
| } |
| 条件装配:满足Conditional指定的条件,则进行组件注入 |

| # 在配置类中使用@Conditional注解 |
| # 如下@ConditionalOnBean(name = "tom")表示容器中有tom实例时,才加载配置类中的组件 |
| # @ConditionalOnMissingBean(name = "tom")表示容器中没有tom实例时,才加载配置类中的组件 |
| |
| @Configuration(proxyBeanMethods = false) |
| |
| @ConditionalOnMissingBean(name = "tom") |
| public class MyConfig { |
| |
| |
| |
| |
| |
| |
| @Bean |
| public User user01(){ |
| User zhangsan = new User("zhangsan", 18); |
| |
| zhangsan.setPet(tomcatPet()); |
| return zhangsan; |
| } |
| |
| @Bean("tom22") |
| public Pet tomcatPet(){ |
| return new Pet("tomcat"); |
| } |
| |
| } |
| |
| # 测试 |
| public static void main(String[] args) { |
| |
| ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); |
| |
| |
| String[] names = run.getBeanDefinitionNames(); |
| for (String name : names) { |
| System.out.println(name); |
| } |
| |
| boolean tom = run.containsBean("tom"); |
| System.out.println("容器中Tom组件:"+tom); |
| |
| boolean user01 = run.containsBean("user01"); |
| System.out.println("容器中user01组件:"+user01); |
| |
| boolean tom22 = run.containsBean("tom22"); |
| System.out.println("容器中tom22组件:"+tom22); |
| |
| } |
| # 当我们的项目中还有xml注册组件时 |
| |
| <?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:context="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 id="haha" class="com.atguigu.boot.bean.User"> |
| <property name="name" value="zhangsan"></property> |
| <property name="age" value="18"></property> |
| </bean> |
| |
| <bean id="hehe" class="com.atguigu.boot.bean.Pet"> |
| <property name="name" value="tomcat"></property> |
| </bean> |
| </beans> |
| |
| # 使用@ImportResource("classpath:beans.xml")将xml文件加载到容器中 |
| # 配置类 |
| @ImportResource("classpath:beans.xml") |
| public class MyConfig {} |
| # 测试类 |
| boolean haha = run.containsBean("haha"); |
| boolean hehe = run.containsBean("hehe"); |
| System.out.println("haha:"+haha);//true |
| System.out.println("hehe:"+hehe);//true |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术