Spring容器支撑xml和properties两种格式文件,在实际开发中,最常使用的就是xml格式的配置方式。这种方式通过xml文件来注册并管理Bean之间的依赖关系
Bean的实例化
常用的分为
1,构造器实例化
2,静态工厂方式实例化
3,实例工厂方式实例化
例:
package com.itheima.instance.factory;
public class Bean3 {
}
package com.itheima.instance.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class INstanceTest3 {
public static void main(String[] args){
String xmlPath = “com/itheima/instance/factory/beans3.xml”;
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean(“bean3”));
}
}
package com.itheima.instance.factory;
public class MyBean3Factory {
public MyBean3Factory() {
System.out.println(“bean3工厂实例化中”);
}
public Bean3 createBean() {
return new Bean3();
}
}
Bean的作用域分为singleton作用域与prototype作用域
Bean的装配方式
Bean类必须提供一个默认的无参构造方法
Bean类必须为需要注入的属性提供对应的setter方法
package com.itheima.assemble;
import java.util.List;
public class User {
private String username;
private Integer password;
private List list;
public User(String username, Integer password, List list) {
super();
this.username = username;
this.password = password;
this.list = list;
}
public User() {
super();
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List list) {
this.list = list;
}
@Override
public String toString() {
return “User [username=” + username + “, password=” + password + “, list=” + list + “]”;
}
}
package com.itheima.assemble;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlBeanAssembleTest {
public static void main(String[] args) {
String xmlPath = “com/itheima/assemble/beans5.xml”;
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean(“user1”));
System.out.println(applicationContext.getBean(“user2”));
}
}
“constructorvalue1”
“constructorvalue2”
“setlistvalue1”
“setlistvalue2”