SpringBoot如何解析Property Placeholder

配置外部化

開發應用的時候,我們經常將一些配置放到properties文件中,這樣當修改這些配置的時候我們可以不用修改源代碼,不用重新打包部署。如果我們的應用基於java config的方式來配置Bean,我們可以使用@PropertySource來指定外部properties文件。

如何引用properties中的property:

  1. 使用Environment API
<code>  
 

public

class

AppConfig

{ Environment env;

public

MyBean

myBean

()

{ MyBean myBean =

new

MyBean(); myBean.setName(env.getProperty(

"bean.name"

));

return

myBean; } } /<code>
  1. 使用@Value
<code> 

@Configuration

@PropertySource

(

"classpath:/com/acme/app.properties"

) public class AppConfig {

@Value

(

"${bean.name}"

) String beanName;

@Bean

public MyBean myBean() {

return

new

MyBean

(beanName); } } /<code>

如何解析property placeholder

但是你知道上面的${...}是如何被解析的嗎? 這就需要用到PropertySourcesPlaceholderConfigurer。該類會將引用的property替換成properties文件中對應的property的值。

Spring Boot 是如何加載PropertySourcesPlaceholderConfigurer

要解析${...}, PropertySourcesPlaceholderConfigurer必須在Spring的 ApplicationContext, 那SpringBoot是如何加載PropertySourcesPlaceholderConfigurer到ApplicationContext呢?

SpringBoot自動裝配的威力就顯現出來了。

<code># Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
        ...       
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
        ...

 
 

public

class

PropertyPlaceholderAutoConfiguration

{

public

static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {

return

new PropertySourcesPlaceholderConfigurer(); } } /<code>



分享到:


相關文章: