SpringBoot复习:(5)使用PropertySource注解

一、自定义的一个配置文件

age=33
name=liu

二、实体类

package com.example.demo.domain;


public class Student {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

三、配置类中使用@PropertySource注解

package com.example.demo.config;

import com.example.demo.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:my.properties")
public class MyConfig {
    @Autowired
    private Environment environment;

    @Bean("student")
    public Student getStudent(){
        Student student = new Student();
        student.setAge(Integer.parseInt( environment.getProperty("age")));
        student.setName(environment.getProperty("name"));
        return student;
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)