Spring執行時候值注入

2022-02-12 12:37:20 字數 1257 閱讀 1743

像這種直接輸入值得方式叫做硬編碼,我們要避免硬編碼值,這時候如果我們想這些書名和作者名在執行時候再確認。

//novel類的構造方法裡面的兩個形參分為書名和作者名

@bean

public book firstbook()

使用@propertysource註解和environment

)//引用了類路徑hj.properties的檔案。

public

class

expressiveconfig

}這個屬性檔案會載入到environment裡面。

hjsjy.properties

hjsjy.title="鬥破蒼穹"

hjsjy.author="天蠶土豆"

我們修改值的時候就在hjsjy.properties檔案修改title和author來實現,這樣就實現了執行時候值注入

使用佔位符($)

"firstbook"

class

="com.spring.hjsjy.book"

c:_titile

=$c:_author

=$/>

public

novel

(@value

("$"

) string title,

@value

("$"

) string author)

使用佔位符要配置乙個propertyplaceholderconfigurerbean,他可以基於spring environment及其屬性源來解析佔位符。

@bean

public

static propertysourcesplaceholderconfigurer placeholderconfigurer()

<

context:property-placeholder

/>

spring 執行時屬性值注入

繼續spring學習,今天介紹兩種外部屬性值注入的方式。當你需要讀取配置資訊時,可以快速讀取。開始之前先建立屬性檔案site.properties,放在classpath下面 資料庫配置 database.oracle.platform org.hibernate.dialect.oracle9id...

Spring執行時注入

1.從屬性檔案中讀取到environment中,再注入。public class superman implements person public string getname configuration componentscan com.kai.vo public class configur...

Spring執行時注入,注入外部的值

使用 propertysourse註解和environment來注入 新建乙個類接收值 public class blankdisc public string gettitle public string getartist disc.title sgtpropper disc.artist th...