SpringXML方式給bean初始化屬性值
阿新 • • 發佈:2019-02-01
可以在Spring容器初始化bean的時候給bean的屬性賦初始值,直接在property標籤裡設定即可
123456 | < bean name = "user**" class = "com.fz.entity.User" > < property name = "id" value = "1" ></ property > < property name = "username" value = "fangzheng" ></ property > < property name = "password" value = "123456" ></ property > < property name = "role1" ref = "role" ></ property > </ bean > |
不過,一般我們自己new的bean是不會這樣做的,而Spring自己的bean則有可能這樣初始化屬性。比如:Spring的連線池
使用String設值
123456 | < bean id = "myDataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method = "close" > < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> < property name = "username" value = "root" /> < property name = "password" value = "masterkaoli" /> </ bean > |
使用Properties設定
123456789 | < bean id = "mappings" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <!-- typed as a java.util.Properties --> < property name = "properties" > < value > jdbc.driver.className=com.mysql.jdbc.Driver </ value > </ property > </ bean > |