版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/84372967
@ConfigurationProperties的使用方式有两种:
- 在类上使用
- 在工厂方法上使用该注解,和@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());
}
}