发表于: 2017-10-24 23:12:15
2 724
今天学习的内容:
百度了一下依赖注入的方式:
spring中的依赖注入DI(dependence injection)共有三种方式:
第一种是接口注入(Interface Injection)
第二种是get set注入(set/get Injection)
第三种是构造器注入(Constructor Injection)。
三种注入方式的区别:
1.接口注入:组件需要依赖特定接口的实现,其中的加载接口实现和接口实现的具体对象都是由容器来完成。这样,接口必须依赖容器,这样的组件具有侵入性,降低了重用性。其中如J2EE开发中常用的Context.lookup(ServletContext.getXXX),都是接口注入的表现形式。(这种注入方式不是常用的)
2.getter/setter方式注入:对于需要注入的东西比较明确。符合java的设计规则。更适合java开发人员,使用起来更加自然,更加方便。
3.构造器方式注入:在类加载的时候,就已经注入依赖的组件。但是若是参数多的话,使用起来不方便。
但是后两种注入方式是spring常用的,而第一种接口注入方式不常用。
用Spring完成了Hello的效果。
定义一个接口:
package com.hpe.hello;
public interface HelloInter {
public void sayHello();
}
定义一个实现接口的类:
package com.hpe.hello;
public class HelloImpl implements HelloInter{
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Hello!");
}
}
配置hello.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- id 表示你这个组件的名字,class表示组件类 -->
<bean id="hello" class="com.hpe.hello.HelloImpl"></bean>
</beans>
定义测试类:
package com.hpe.hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void testHelloWorld() {
//1、读取配置文件实例化一个IoC容器
ApplicationContext context= new ClassPathXmlApplicationContext("hello.xml");
//2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
HelloImpl helloImpl = (HelloImpl) context.getBean("hello",HelloInter.class);
//3、执行业务逻辑
helloImpl.sayHello();
}
}
结果:
问题:对依赖注入的三种方式不是很明白。
明天继续学习Spring。
评论