Spring5:Java Config
2024-10-09 02:44:34
@Configuration
@Bean
@ComponentScan
@ImportResource
使用Java的方式配置spring,完全不使用spring配置文件,交给java来做!
两个注解非常重要:
@Configuration:相当于创建了spring配置文件的beans标签
@Bean:实例化对象 相当于创建了spring配置文件bean标签
定义一个Person 对象
package com.spring.Vo2;
import org.springframework.beans.factory.annotation.Value;
public class Person {
@Value("king")
private String name;
public String getName() {
return name;
}
}
创建一个配置类MyConfig :bean的id就是方法名称
package com.spring.confing;
import com.spring.Vo2.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public Person person(){
return new Person();
}
}
测试:
通过AnnotationConfigApplicationContext对象获取Spring容器
@Test
public void test03(){
//获取容器 AnnotationConfigApplicationContext
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(MyConfig.class);
//获取bean
Person person =applicationContext.getBean("person", Person.class);
System.out.println(person.getName());
}
扩展功能:扫描、合并注解
@Configuration
@ComponentScan(value = "com.spring.confing")
@ImportResource(value =MyConfig2.class )
最新文章
- 和Java相关的书籍,想成为架构师的请收藏一下啊
- WinCE非通用调试工具汇总
- iOS:iOS中的多控制器管理
- jQuery validate兼容IE8写法
- 第 27 章 CSS 传统布局[上]
- window内存管理与内存原理
- PHP动态函数
- SQL Server 日志清除
- 【POJ】【2068】Nim
- VB.NET中DataGridView控件
- codeforces 几道题目
- Python基础学习 -- 列表与元组
- 14 Fragment 碎片总结
- js-webpack自动化构建工具
- php_network_getaddresses: getaddrinfo failed 原因
- mysql 开发进阶篇系列 22 磁盘I/O问题(从linux操作系统上优化)
- 认识不一定熟悉的opencv
- 第二次作业:Git的安装与使用
- HTTP 的长连接和短连接
- kafka definitive guide - reading notes