一、创建Spring项目
添加maven依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
二、编写Bean及配置类
1.配置文件:
在类路径(编译完成后,class文件的根目录)下创建person.properties文件(一般放在resources目录下,resources目录下的文件会放在类路径下)
person.name=迪丽热巴
person.age=27
2.Bean类
使用@Value加$取出配置文件的值
public class Person {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3.配置类:
@Configuration表示这个类为配置类,使用@Bean注册Person组件,使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中
@PropertySource(value = {"classpath:/person.properties"}, encoding = "utf-8")
@Configuration
public class BeanConfig {
@Bean
public Person person() {
return new Person();
}
}
三、测试
public class MyMain {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
}
}
结果: