一、配置文件的加载
/*
* 加载自定义配置文件数据
*/
@PropertySource(value)
自定义创建targetData.properties
接着在po包下创建一个实体类user
public class User {
private String name;
private Integer age;
private Integer gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
}
再回到target.properties文件中,编写数据信息,对应user类中的属性如下所示:
user.name=oolee
user.age=20
user.gender=1
然后在user类上添加三个注解;
/**
* @Component bean对象
* @PropertySource(value = "classpath:targetData.properties")加载配置文件
* @ConfigurationProperties(prefix = "user") 读取配置文件数据
*/
@Component
@PropertySource(value = "classpath:targetData.properties")
@ConfigurationProperties(prefix = "user")
这里是利用@PropertiesSource通过类路径加载配置文件
最后通过测试类输出对象user
运行得到结果
二、配置文件的导入
springboot中如果需要编写spring配置文件,那么有两种方法。
第一种就是传统的方式:编写xml文件,像spring bean一样通过<bean>标签声明一个bean。
此方法需要在springboot主程序类上添加一下注解
@ImportResource(locations)
springboot程序默认只会加载application.properties和application.yml两种形式配置文件,对于自定义的配置文件必须在主程序上通过@ImportResource注解导入
第二种就是编写配置类(推荐使用):
@Configuration表示这是一个配置类
@Bean表示该方法是一个bean对象,方法名为bean的id,返回对象是bean的值
下面来看示例:
首先创建一个UserService接口,以及接口实现类UserServiceImpl
package com.clyh.service;
public interface UserService {
public void show();
}
package com.clyh.service.serviceImpl;
import com.clyh.service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void show() {
System.out.println("hello configuration");
}
}
接着在创建一个配置类,配置类上用@Configuration注解,同时类中再创建一个方法,方法用@Bean注解
package com.clyh.config;
import com.clyh.service.serviceImpl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration表示这是一个配置类
* @Bean表示该方法是一个bean对象,方法名为bean的id,返回对象是bean的值
*/
@Configuration
public class configOne {
/**
* 相当于
* <bean id="userService" class="com.clyh.service.serviceImpl.UserServiceImpl"></bean>
* @return
*/
@Bean
public UserServiceImpl userService(){
return new UserServiceImpl();
}
}
测试类:
package com.clyh.test;
import com.clyh.po.User;
import com.clyh.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TargetTest {
@Autowired
User user;
@Autowired
ApplicationContext ac;
@Test
public void load(){
Boolean re = ac.containsBean("userService");
System.out.println(re);
UserService ob = (UserService)ac.getBean("userService");
ob.show();
}
}
运行结果: