一、在application.properties中定义属性:
my.firstName=amadeus1756
my.lastName=liu
二、定义实体类
package cn.edu.tju.domain;
public class AnotherComponent {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
三、在配置类的bean定义中使用@ConfigurationProperties
package cn.edu.tju.config;
import cn.edu.tju.domain.AnotherComponent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig3 {
@Bean
@ConfigurationProperties(prefix = "my")
public AnotherComponent getAnotherComponent(){
return new AnotherComponent();
}
}
四、在controller中注入上述bean,并使用
@Autowired
private AnotherComponent anotherComponent;
@RequestMapping("getAnother")
public String getAnother(){
return anotherComponent.getFirstName();
}
|