IOC创建对象的方式
通过无参构造方法来创建(默认)
User.java
public class User {
private String name;
public User ( ) {
System. out. println ( "User无参构造方法" ) ;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public void show ( ) {
System. out. println ( "name=" + name) ;
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
< bean id = " user" class = " site.duing.pojo.User" >
< property name = " name" value = " 张三" />
</ bean>
</ beans>
测试
@Test
public void test ( ) {
ApplicationContext context = new ClassPathXmlApplicationContext ( "beans.xml" ) ;
User user = ( User) context. getBean ( "user" ) ;
user. show ( ) ;
}
结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了
通过有参构造方法来创建
UserT.java
public class UserT {
private String name;
public UserT ( String name) {
System. out. println ( "UserT有参构造方法" ) ;
this . name = name;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public void show ( ) {
System. out. println ( "name=" + name) ;
}
}
beans.xml 有三种方式编写
< bean id = " userT" class = " site.duing.pojo.UserT" >
< constructor-arg index = " 0" value = " 李四" />
</ bean>
< bean id = " userT" class = " site.duing.pojo.UserT" >
< constructor-arg name = " name" value = " 李四" />
</ bean>
< bean id = " userT" class = " site.duing.pojo.UserT" >
< constructor-arg type = " java.lang.String" value = " 李四" />
</ bean>
测试
@Test
public void test ( ) {
ApplicationContext context = new ClassPathXmlApplicationContext ( "beans.xml" ) ;
UserT userT = ( UserT) context. getBean ( "userT" ) ;
userT. show ( ) ;
}
发现:虽然没有调用User类,但是也创建了User对象 结论:在配置文件加载的时候。其中管理的对象都已经初始化了
Spring配置
别名
alias设置别名 , 为bean设置别名 , 可以设置多个别名
< alias name = " userT" alias = " userNew" />
Bean的配置
< bean id = " hello" name = " hello2 h2,h3;h4" class = " site.duing.pojo.Hello" >
< property name = " name" value = " Spring" />
</ bean>
import
一般用于团队来发使用,他可以将多个配置文件导入合并为一个 假设,现在项目中有如下三个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们乐意利用import将所有人的beans.xml合并为一个总的 张三 李四 王五 applicationContext.xml
< import resource = " {path}/beans1.xml" />
< import resource = " {path}/beans2.xml" />
< import resource = " {path}/beans3.xml" />
使用的时候,直接使用总的这个applicationContext.xml 配置文件就行了
下一篇:《Spring学习(4)——DI依赖注入》