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

  • Post author:
  • Post category:其他


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

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;
    }
}



版权声明:本文为amadeus_liu2原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。