详解SpringBean基于XML的装配1.设值注⼊:通过反射调⽤setXxx注⼊属性值
package com.itheima.assemble;
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
/**
* 设值注⼊
* 提供默认空参构造⽅法 ;
* 为所有属性提供setter⽅法。
*/
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password +
", list=" + list + "]";
}
}
package com.itheima.assemble;
import t.ApplicationContext;
import
t.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/l";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
// 构造⽅式输出结果
System.out.Bean("user2"));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans-4.3.xsd">
<!--2.使⽤设值注⼊⽅式装配User实例 -->
<bean id="user2" class="com.itheima.assemble.User">
<property name="username" value="张三"></property>
<property name="password" value="654321"></property>
<!-- 注⼊list集合 -->
<property name="list">
<list>
<value>"值1"</value>
<value>"值2"</value>
</list>
</property>
</bean>
</beans>
2.构造注⼊:⽤+其value属性注⼊属性值
package com.itheima.assemble;
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
/**
* ⽤构造注⼊
* 创建带所有参数的有参构造⽅法。
*/
public User(String username, Integer password, List<String> list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password +
", list=" + list + "]";
spring怎么读取xml文件}
}
package com.itheima.assemble;
import t.ApplicationContext;
import
t.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/l";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
// 构造⽅式输出结果
System.out.Bean("user1"));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans-4.3.xsd">
<!--1.使⽤构造注⼊⽅式装配User实例user1,装配后user1则内含多个注⼊数据的属性 -->
<bean id="user1" class="com.itheima.assemble.User">
<constructor-arg index="0" value="tom" /><!-- 属性1,即username -->
<constructor-arg index="1" value="123456" /> <!-- 属性2,即password -->
<constructor-arg index="2"> <!-- 属性3 -->
<list>
<value>"值1"</value>
<value>"值2"</value>
</list>
</constructor-arg>
</bean>
</beans>
到此这篇关于详解SpringBean基于XML的装配的⽂章就介绍到这了,更多相关SpringBean装配内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论