IOC
- IOC即控制反转,使用IOC我们不用再一一创建对象来调用对象实例,这个创建的任务就交给了IOC容器来完成。下面我写了一些例子
- 在main方法里创建IOC容器,顺便输出一些注入内容:
- AplicationContext
package Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ManagerTest {
public static void main(String[] arg) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
User u=(User)ctx.getBean("first");
}
}
- 依赖注入(注入实例)
- Setter注入:
1、创建JavaBean
如:
package Test;
public class User {
private String name;
private String sex;
public User() {
super();
System.out.print("Ok");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2、配置文件:
<bean name="user" class="com.mr.User ">
<property name="name">
<value>老王</value>
</property>
....
</bean>
构造器注入:
1.JavaBean需要提供有参的构造方法
2.配置文件就不用l了,使用
<constructor-arg>
<value></value>
</constructor-arg>
引用别的Bean:
直接上code:
package Test;
public class FirstTest {
private String name;
private String sex;
private First_ f_;
public FirstTest() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "FirstTest [name=" + name + ", sex=" + sex + ", f_=" + f_ + "]";
}
public First_ getF_() {
return f_;
}
public void setF_(First_ f_) {
this.f_ = f_;
}
}
另一个JavaBean:
package Test;
public class First_ {
private String job;
public String getName() {
return job;
}
public void setName(String job) {
this.job = job;
}
public First_() {
super();
}
@Override
public String toString() {
return "First_ [job=" + job + "]";
}
}
关键一步,配置文件:
<?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="first" class="Test.FirstTest">
<property name="name" >
<value>蝙蝠侠</value>
</property>
<property name="sex">
<value>男</value>
</property>
<property name="f_" ref="f_2"></property><!-- 主要是这里,这个name的值要跟第一个JavaBean的对象名一样 -->
</bean>
<bean id="f_2" class="Test.First_">
<property name="name">
<value>超级英雄</value>
</property>
</bean>
</beans>
再写一个main方法输出看效果:
package Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ManagerTest {
public static void main(String[] arg) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
FirstTest f=(FirstTest)ctx.getBean("first");
First_ f_=(First_)ctx.getBean("f_2");
System.out.print(f.toString());
}
}
输出图: