JavaConfig
JavaConfig
配置文件
Xml 和 JavaConfig
- Spring 使用 Xml 作为容器配置文件
- 需要写大量配置文件
- 还要配置各种对象,将使用的对象放到 Spring 容器才能使用
- 需要了解其他框架配置规则
- 在 3.0 之后加入 JavaConfig,使用 Java 类做配置文件使用
@Configuration
- Spring 提供的使用 Java 类配置容器
- 使用 Java 类作为 xml 配置文件的替代
- 在类中可创建对象,将对象注入容器
- 配置 Spring IOC 容器的纯 Java 方法
- 使用 Java 类作为 xml 配置文件的替代
- 优点
- 可使用面向对象方式:一个配置类可以继承配置类,可以重写方法
- 避免繁琐的 xml 配置
- 使用注解
@Configuration
- 注解类上面,表示该类作为配置文件使用
@Bean
- 声明对象,把对象注入到容器
- 通过 name 或 value 属性指定对象名
- 默认对象名是 方法名
/**
* @Configuration 表示当前类作为配置文件使用
* 相当于 配置文件
*/
@Configuration
public class Conf {
/**
* 创建方法,返回值是对象
* @Bean 注解将对象注入到 Spring 容器,相当于 <bean></bean> 的作用
* 默认对象名是方法名,使用注解属性 name 或 value 指定对象名:等价于指定 <bean> 的 id
* @return 返回对象,注入到容器
*/
@Bean(name = "demo")
public Demo getDemo(){
Demo demo = new Demo();
demo.setName("李四");
demo.setAge(18);
demo.setBirthday(new Date());
demo.setHobby("篮球");
return demo;
}
}
@ImportResource
- 导入资源配置文件,等同于 xml 文件的
<resources>
标签 - 注解在类定义上
- 导入配置文件中的 bean 对象
- 属性 value、location 作用一样,都是指定配置文件位置
- 属性为数组类型,多个配置文件可以使用数组添加
@Configuration
@ImportResource({"classpath:applicationContext.xml", "classpath:bean.xml"})
public class Conf {}
@PropertyResource
- 读取 properties 属性配置文件
- 例如数据路连接信息的配置文件
- 实现外部化配置,在程序代码之外提供数据
@PropertySource
- 属性 value 指定配置文件路径,数组类型,可以同时指定多个文件
@ComponentScan
- 该注解类似组件扫描器
- 扫描通过注解创建的对象
- 属性 value、basePackages 指定注解所在包
- 自动找到指定包下的注解并创建对象放到 Spring 容器中
- 该注解类似组件扫描器
@Value
- 给类中属性赋值
${}
:占位符,通过配置文件赋值
@Configuration // 该类作为配置类使用
@PropertySource(value = "classpath:pro.properties", encoding = "UTF-8") // 以 UTF-8 编码格式导入外部属性配置文件
@ComponentScan(basePackages = "demo.domain") // 声明注解扫描,扫描并创建容器对象
public class Conf {}
@Component("demo03") // 普通Java类,通过注解声明放入容器中
public class Demo03 {
@Value("${name}") // 占位符;引用配置文件中值进行赋值
private String name;
@Value("${age}")
private int age;
@Autowired
private Date birthday;
@Value("${hobby}")
private String hobby;
简单使用
@Configuration // 表示当前类作为配置文件使用
@ImportResource("classpath:applicationContext.xml") // 导入外部资源配置文件中的 bean 对象
@PropertySource(value = "classpath:pro.properties", encoding = "UTF-8") // 导入外部属性配置文件,指定配置文件路径
@ComponentScan(basePackages = "demo.domain") // 组件扫描器,扫描注解,创建对象;指定注解所在包
public class Conf {
/**
* 创建方法,返回值是对象
* @Bean 将对象注入到 Spring 容器,相当于 <bean></bean> 作用
* 默认对象名是方法名,使用注解属性 name 或 value 指定对象名:指定 <bean> 的 id
* @return 返回对象,注入到容器
*/
@Bean(name = "demo02")
public Demo02 getDemo(){
Demo02 demo = new Demo02();
demo.setName("张二");
demo.setAge(19);
demo.setHobby("rap");
demo.setBirthday(new Date());
return demo;
}
}