Objective
===========================================
Initial contact with spring Boot
===========================================
A custom property value in the resource file, configured on an object bean, and then used in the program to use the Bean's property values.
One.
Two.
@Component
Flag This class is a bean
@PropertySource (value = "Classpath:/application.properties")
Specifies which resource file to bind to, "If you want to bind the value in the custom resource file, it can be used on the" Here the Application.properties file is the springboot default resource file, it can not be specified, here binding words, will go to load binding two times.
@ConfigurationProperties (prefix = "com.sxd")
Specifies the name of the attribute in the binding resource file that begins with the prefix com.sxd, and the others are not bound. Because the Location property is canceled here, the above annotation is used as an alternative
PackageCom.sxd.beans;Importorg.springframework.boot.context.properties.ConfigurationProperties;ImportOrg.springframework.context.annotation.PropertySource;Importorg.springframework.stereotype.Component; @Component @propertysource (Value= "Classpath:/application.properties") @ConfigurationProperties (prefix= "Com.sxd") Public classConfigbean {PrivateString name; PrivateString want; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getwant () {returnwant; } Public voidsetwant (String want) { This. want =want; }}
View Code
Three.
@EnableConfigurationProperties (Configbean.class)
Activating a bound bean
@Autowired
Automatic injection of a bound bean
PackageCom.sxd.firstdemo;ImportCom.sxd.beans.ConfigBean;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.boot.context.properties.EnableConfigurationProperties;Importorg.springframework.web.bind.annotation.RequestMapping;Importorg.springframework.web.bind.annotation.restcontroller;@ Restcontroller@springbootapplication@enableconfigurationproperties (Configbean.class) Public classfirstdemoapplication {@Autowired Configbean configbean; @RequestMapping ("/") PublicString Index () {return"Hello Spring Boot," +Configbean.getname (); } Public Static voidMain (string[] args) {Springapplication.run (firstdemoapplication.class, args); }}
View Code
Four.
Operation Result:
"Spring Boot" Spring boot1.5 or later @configurationproperties cancellation of location annotations alternatives