项目结构
pom.xml
4.0.0 test.demo springboot 0.0.1-SNAPSHOT jar springboot org.springframework.boot spring-boot-starter-parent 1.3.0.RELEASE UTF-8 org.springframework.boot spring-boot-starter-web
@Configurationproperties注解和@Value注解
@ConfigurationProperties加在有@Configuration的类或者由@Bean注解的方法上,
另外一个类似的注解@EnableConfigurationProperties
用于允许@ConfigurationProperties
使用示例:
package hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App{ public static void main(String[] args) { SpringApplication.run(App.class, args); }}
package hello.bean;//@Configuration//@ConfigurationProperties("user.properties")public class TestBean{ 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; }}
package hello.config;import hello.bean.TestBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class BeanConfig{ @ConfigurationProperties("user.properties") @Bean public TestBean getBean() { return new TestBean(); }}
package hello.controller;import hello.bean.TestBean;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class Controller{ @Autowired TestBean bean; @Value("${user.properties.name}") String name; @RequestMapping(value = "/test", method = RequestMethod.GET) public String get() { System.out.println(name); return bean.getName(); } @RequestMapping(value = "/post", method = RequestMethod.POST) public String post() { return "post"; }}
application.yml
user: properties: age: 18 name: zzzz
单个属性使用@Value
posted on 2016-03-11 15:08 阅读( ...) 评论( ...)