One
The intuitive injection values for beans are as follows:
@Bean Public Compactdisc sgtpeppers () { returnnew blankdisc ( "Sgt. Pepper ' s Lonely Hearts Club Band ", " the Beatles "); < Bean id = "Sgtpeppers"class = "Soundsystem". Blankdisc "=" Sgt. Pepper ' s Lonely Hearts Club Band "=" The Beatles "/>
Are all in hard-coded form, Spring provides two ways to run the in-injection (1) property placeholders (2) the Spring Expression Language (S p EL)
Second, property placeholders
1.app.properties
1 disc.title=Sgt peppers Lonely Hearts Club Band2 disc.artist=the Beatles
2.
1 PackageCom.soundsystem;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 ImportOrg.springframework.context.annotation.Bean;5 Importorg.springframework.context.annotation.Configuration;6 ImportOrg.springframework.context.annotation.PropertySource;7 Importorg.springframework.core.env.Environment;8 9 @ConfigurationTen@PropertySource ("Classpath:/com/soundsystem/app.properties") One Public classEnvironmentconfig { A - @Autowired - Environment env; the - @Bean - PublicBlankdisc Blankdisc () { - return NewBlankdisc ( +Env.getproperty ("Disc.title"), -Env.getproperty ("Disc.artist")); + } A at}
3.
1<?xml version= "1.0" encoding= "UTF-8"?>2<beans xmlns= "Http://www.springframework.org/schema/beans"3Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4Xmlns:c= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/C"5xmlns:context= "Http://www.springframework.org/schema/context"6xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd7http//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd">8 9<context:property-placeholderTenlocation= "Com/soundsystem/app.properties"/> One A<beanclass= "Com.soundsystem.BlankDisc" -C:_0 = "${disc.title}" -C:_1 = "${disc.artist}"/> the -</beans>
Iii. further discussion of Spring's E nvironment
GetProperty () is overloaded to four variations:
? String GetProperty (String key)
? String GetProperty (String key, String defaultvalue)
? T GetProperty (String key, class<t> type)
? T GetProperty (String key, class<t> type, T defaultvalue)
Given default value
@Bean Public Blankdisc disc () { returnnew Blankdisc ( env.getproperty ("Disc.title", "Rattle and Hum"), env.getproperty ("Disc.artist", "U2");}
Automatic transformation
int connectioncount =env.getproperty ("Db.connection.count", Integer. Class, 30);
@Bean Public Blankdisc disc () {returnnew Blankdisc (Env.getrequiredproperty ("Disc.title" ) , Env.getrequiredproperty ("disc.artist"));}
Here, if either the Disc.title property or the Disc.artist property was undefined, an
IllegalStateException'll be thrown.
Check for Presence
boolean titleexists = Env.containsproperty ("Disc.title");
SPRING in ACTION 4th Note-Chapter advancing wiring-006-inject value to Bean runtime (environment,property file)