SpringBoot详解(一)xml和JavaConfig
第一章 Xml和JavaConfig
- 为什么要使用SpringBoot
- 因为Spring,Spring需要使用的大量的配置文件(xml文件)
resources目录下/beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 声明bean对象-->
<bean id="myStudent" class="com.firewolf.vo.Student">
<property name="name" value="李思"/>
<property name="age" value="20"/>
<property name="sex" value="女"/>
</bean>
</beans>
- 还需要配置各种对象,把使用的对象放入到Spring容器中才能使用对象。
- 需要了解其他框架的配置规则。
- SpringBoot就相当于不需要配置文件的spring+springmvc。常用的框架和第三方库都配置好了。拿来就可以使用。
- Springboot开发效率高,使用方便。
1.1 JavaConfig
Javaconfig:使用java类作为xml配置文件的替代,是配置spring容器的纯java的方式。在这个Java类中可以创建java对象,把对象放入spring容器中(注入到容器)。
使用两个注解
- @Configuration : 放在类的上面,表示这个类是作为配置文件使用的。
- @Bean : 声明对象,把对象注入到容器中。
package com.firewolf.config;
import com.firewolf.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration:表示当前类作为配置文件使用的。就是用来配置容器的。
* 位置:在类的上面
*
* SpringConfig这个类就相当于beans.xml
*
* **/
@Configuration
public class SpringConfig {
/**
* 创建方法,方法的返回值是对象。在方法的上面加入@Bean
* 方法的返回值对象就注入到容器中。
*
* @Bean: 把对象注入到spring的容器中。作用相当于<bean>
* 位置:方法的上面。
*
* 说明:@Bean,不指定对象的名称,默认是方法名是id.
* **/
@Bean
public Student createStudent(){
Student s1= new Student();
s1.setName("张三");
s1.setAge(26);
s1.setSex("男");
return s1;
}
/**
* 指定对象在容器中的名称(指定<bean>的id属性)
* @Bean 的name 属性,指定对象的名称(id)
* **/
@Bean(name = "lisiStudent")
public Student makeStudent(){
Student s2= new Student();
s2.setName("李四");
s2.setAge(22);
s2.setSex("男");
return s2;
}
}
1.2 ImportResource
@ImportResource 作用导入其他的xml配置文件,等于在xml。
<import resources="其他配置文件"/>
@Configuration
@ImportResource(value = {"classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {
}
1.3 @PropertyResource
@PropertyResource:读取properties属性文件。使用属性配置文件可以实现外部化配置,在程序代码之外提供数据。 PS:文件中要使用中文的话要设置编码格式!
步骤:
- 在resources目录下,创建properties文件,使用k=v的格式提供数据。
tiger.name=东北虎
tiger.age=3
- 在PropertyResources 指定properties文件的位置。
@Configuration //相当于配置文件
@ImportResource(value = {"classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.firewolf.vo")
public class SpringConfig {
}
- 使用@Value(value="${key}")
package com.firewolf.vo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("tiger")
public class Tiger {
@Value("${tiger.name}")
private String name;
@Value("${tiger.age}")
private Integer age;
}