Spring之@ConfigurationProperties註解

@ConfigurationProperties的使用方式有兩種:

  1. 在類上使用
  2. 在工廠方法上使用該註解,和@Bean一起使用

1.在類上使用:

創建一個People實體類:

package com.config.server.endpoint;


public class People {
    private String username;
    private String password;
    private int age;
    private int sex;

	//省略seter、getter方法
}

在配置文件application.properties添加屬性:

com.yaomy.demo.username=瑪麗
com.yaomy.demo.password=123456
com.yaomy.demo.age=12
com.yaomy.demo.sex=1

在工廠方法上使用@ConfigurationProperties註解:

package com.config.server;

import com.config.server.endpoint.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@EnableConfigServer
@SpringBootApplication
public class ServerApplication {

    @Bean(name = "my-bean-test1")
    @ConfigurationProperties(prefix = "com.yaomy.demo")
    public People getBean(){
        return new People();
    }
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
        People obj = context.getBean("my-bean-test1", People.class);
        System.out.println(obj.getUsername());
        People obj1 = context.getBean("my-bean-test1", People.class);
        System.out.println(obj1.getSex());
    }
}

2.在工廠方法上使用該註解,和@Bean一起使用:

創建一個People實體類:

package com.config.server.endpoint;


import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "com.yaomy.demo")
public class People {
    private String username;
    private String password;
    private int age;
    private int sex;

	//省略getter setter方法
}

在工廠方法上使用@ConfigurationProperties註解:

package com.config.server;

import com.config.server.endpoint.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@EnableConfigServer
@SpringBootApplication
public class ServerApplication {

    @Bean(name = "my-bean-test1")
    public People getBean(){
        return new People();
    }
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
        People obj = context.getBean("my-bean-test1", People.class);
        System.out.println(obj.getUsername());
        People obj1 = context.getBean("my-bean-test1", People.class);
        System.out.println(obj1.getSex());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章