可以在Spring容器初始化bean的时候给bean的属性赋初始值,直接在property标签里设置即可
1 2 3 4 5 6 | < 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设值
1 2 3 4 5 6 | < 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设置
1 2 3 4 5 6 7 8 9 | < 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 jdbc.url=jdbc:mysql://localhost:3306/mydb </ value > </ property > </ bean > |