Spring Boot read configuration properties

1.@Value

Array property in the configuration file using comma separated, One thing to note: controller layer properties acquired in spring frameworks are needed to add properties file references in the spring and springmvc configuration files, property files can not be read when otherwise started. Configuration properties can be directly acquired in the controller layer springboot.

2.Environment

Environment objects obtained by injection, and then acquires the attribute value defined in the configuration file; Environment object by obtaining or acquiring the value after ApplicationContext

@RestController
public class ConfigureController extends BaseController{
    private static final String MINE_HELLO="mine.hello";
    private static final String MINE_INT_ARRAY="mine.int-array";
    @Resource
    private Environment env;
    @RequestMapping("config")
    public void config(){
        String a=applicationContext.getEnvironment().getProperty(MINE_HELLO);
        String c=applicationContext.getEnvironment().getProperty(MINE_INT_ARRAY);
        System.out.println(a);
        System.out.println(c);
    }
    @RequestMapping("envir")
    public void envir(){
        String a=env.getProperty(MINE_HELLO);
        String c=env.getProperty(MINE_INT_ARRAY);
        System.out.println(a);
        System.out.println(c);
    }
}

Here BaseController injecting a ConfigurableApplicationContext object. Acquired properties are of type String

3.@ConfigurationProperties

@ConfigurationProperties acts on class for injecting property Bean, Bean then acquired by the current value injected

@RestController

public class PropertiesController {
    @Autowired
    private Attribute attribute;
    @RequestMapping("property")
    public void property(){
        System.out.println(attribute.getHello());
        System.out.println(Arrays.toString(attribute.getIntArray()));
    }
}
@Component
//@PropertySource("classpath:application.yaml")
@ConfigurationProperties(prefix = "mine")
class Attribute{
    private String hello;
    private Integer[] intArray;

    public void setHello(String hello) {
        this.hello = hello;
    }

    public void setIntArray(Integer[] intArray) {
        this.intArray = intArray;
    }

    public String getHello() {
        return hello;
    }

    public Integer[] getIntArray() {
        return intArray;
    }
}

I attribute named int-array, you can still get a property hump nomenclature Attribute class

PropertiesLoaderUtils, temporarily understand

Guess you like

Origin www.cnblogs.com/psxfd4/p/11975718.html