您的位置:首页 > 编程语言 > Java开发

【spring】IOC入门

2012-09-30 09:19 148 查看
spring的核心概念之一:控制反转——IOC
控制反转简单来说就是,依赖接口,把控制权移至接口
不依赖实现,高层模块不依赖于底层模块

spring是非侵入的,通过使用IOC,对象是不主动去找而是被动接收依赖类的
以此来实现松耦合

控制反转通过依赖注入实现,而常见的实现方式也有三种:接口注入,setter方法注入,构造注入

example_1:通过setter方式来实现对象注入
//定义接口:
public interface BeanBase {
void show();
}
//实现类:
public class MyBean implements BeanBase {
public void show() {
System. out.println(" is my bean" );
}
}
//BeanTest类,其中定义将会注入对象的接口引用
public class BeanTest {
private BeanBase bean;

public BeanBase getBean() {
return bean ;
}

public void setBean(BeanBase bean) {
this.bean = bean;
}
}
//demo:通过从配置文件来读取要注入的对象
public class SpringDemo2 {
private static final Logger mylog = Logger.getLogger(SpringDemo2.class.getName());
public static void main(String[] args) {

Resource re = new ClassPathResource("com\\ming\\sns\\test\\bean-config.xml" );
mylog.info(re);
BeanFactory bf = new XmlBeanFactory(re);
BeanTest bean = (BeanTest) bf.getBean( "BeanTest");
mylog.info(bean);
bean.getBean().show();
}
}
//配置文件,在配置文件便签< property中实现setter方法进行对象的注入,注入的是MyBean对象
<?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-3.0.xsd" >

<bean id= "BeanBase" class ="com.ming.sns.test.MyBean"></ bean>
<bean id= "BeanTest" class ="com.ming.sns.test.BeanTest">
<property name="bean" >
<ref bean="BeanBase" />
</property>
</bean>
</beans>


example_2:通过方法注入
//构建需要注入的类对象
public class BeanTest3 {
private String message;
public BeanTest3() {
this.message = " test: " + new java.util.Date().toString();
}

public String toString() {
return this .message ;
}
}
//需要注入的类对象,与BeanTest3存在依赖的关系
public abstract class MyFactory2 {
public abstract BeanTest3 create();
public void show() {
BeanTest3 bean = create();
System. out.println(bean);
}
}
//demo,通过配置文件注入MyFactory2 对象,然后在show方法里注入BeanTest3
//对BeanTest3 对象设置了非singleton属性
public class SpringDemo5 {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("com\\ming\\sns\\test\\bean-config.xml" );
MyFactory2 test = (MyFactory2) context.getBean( "MyFactory2");
test.show();

}
}
//配置文件,本例需要添加CGLIB 的jar包
//配置了CGLIB的jar包,能够为我们动态生成需要的class
<?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-3.0.xsd" >
<!-- default-autowire="byName" default-lazy- init="true"> -->
<bean id= "BeanTest3" class ="com.ming.sns.test.BeanTest3" scope="prototype" ></bean>
<bean id= "MyFactory2" class ="com.ming.sns.test.MyFactory2">
<lookup-method name="create" bean="BeanTest3"/>
</bean>
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: