Injection configuration content
Add application.yml the attribute values, for example:
# Property values read from the configuration file age: 26 gName: lisa content: "age: ${age},aName: ${gName}"
Use @Value removed in ContentController
// Use @value annotation value achieved injection configuration content @Value ( "Age $ {}" ) Private Integer Age; @Value("${gName}") private String name; @Value("${content}") private String content;
Again amend application.yml, examples are as follows:
server: port: 8081 person: age: 26 gName: lisa
By @ Component, @ ConfigurationProperties injection configuration, for example:
package com.rongrong.springboot.demo; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author rongrong * @version 1.0 * @description: * @date 2019/12/28 13:56 */ @Data // injection configuration @Component @ConfigurationProperties(prefix = "person") public class Person { private Integer age; private String gName; }
In the Controller, taken over the same bean
package com.rongrong.springboot.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author rongrong * @version 1.0 * @description: * @date 2019/12/26 20:34 */ @RestController public class HellowController { @Autowired Person person; @RequestMapping(value = "/hellow",method = RequestMethod.GET) public String say(){ return person.getGName(); } }
Start the project, by accessing the HTTP: // localhost: 8081 / hellow , page effect is as follows:
Multi-environment configuration
Yml create two files,
application-dev.yml
server: port: 8081 person: age: 26 gName: lisa
application-prod.yml
server: port: 8888 person: age: 18 gName: tony
Controlled by application.yml, a modified example as follows:
# Multi-environment configuration
spring:
profiles:
active: prod
Verify multi-context switching is correct
We use the command line to start the test, the first implementation mvn install package
Positioning the target, entering the command to switch to the environment dev
java -jar springboot_demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
effect:
Enter the following commands to switch to the environment prod
java -jar springboot_demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
effect: