package com.bean;
public class Product {
public Product(int id, String name) {
this.id = id;
this.name = name;
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
通过setXXX、getXXX注入
<bean name="product" class="com.bean.Product"> <property name="id" value="1" /> <property name="name" value="admin" /> </bean>
通过构造方法注入
<bean name="product" class="com.bean.Product"> <constructor-arg index="0" type="int" value="1" /> <constructor-arg index="1" type="java.lang.String" value="测试" /> </bean>
//通过p:name注入(属性)
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="masterkaoli"/>
</beans>
//通过properties形式注入
<bean id="mappings"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<value>
jdbc.driver.className=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
</value>
</property>
</bean>
//内部bean注入
<bean id="outer" class="...">
<property name="target">
<bean class="com.example.Person"> <!-- this is the inner bean -->
<property name="name" value="Fiona Apple"/>
<property name="age" value="25"/>
</bean>
</property>
</bean>
//注入集合
<bean id="moreComplexObject" class="example.ComplexObject">
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.org</prop>
<prop key="support">support@example.org</prop>
<prop key="development">development@example.org</prop>
</props>
</property>
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource" />
</list>
</property>
<property name="someMap">
<map>
<entry key="an entry" value="just some string"/>
<entry key ="a ref" value-ref="myDataSource"/>
</map>
</property>
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource" />
</set>
</property>
</bean>
//注入空值和""
<bean class="ExampleBean">
<property name="email"><null/></property>
</bean>
<bean class="ExampleBean">
<property name="email" value=""/>
</bean>
//通过c:name注入(构造函数)
<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz">