简单的Spring容器注入和三种依赖注入(一)
IoC注入主要分为3种:构造函数注入、属性注入、接口注入。Spring支持前两种,
下面我分别实现一下这几种注入方法。
一、容器注入方式(Spring)。
1、简单注入
首先我们建一个bean.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-2.5.xsd"><bean id="userService" class="com.xtfggef.service.impl.UserServiceImpl"/></beans>
还需要一个Java类UserServiceImpl.java
package com.xtfggef.service.impl;public class UserServiceImpl {public void add(){System.out.println("this is add()");}}然后建junit测试:
package com.xtfggef.junit.test;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import com.xtfggef.service.impl.UserServiceImpl;public class StringJunitTest {public static BeanFactory factory;@BeforeClasspublic static void setUpBeforeClass() throws Exception {Resource res = new ClassPathResource("bean.xml");factory = new XmlBeanFactory(res);}@Testpublic void test() {UserServiceImpl userService = (UserServiceImpl) factory.getBean("userService");userService.add();}}这样就注入成功了。这是一种最简单的方法,需要读取配置文件。
2、下面是Spring对构造函数注入和属性注入的实现。
二、通常IoC注入方式。
1、构造函数注入
一个接口UserService.java
public interface UserService {public void add();}一个实现类UserServiceImpl.java
public class UserServiceImpl implements UserService {public void add(){System.out.println("this is add()");}}将要注入的类UserAction.java(注意:此Action非Struts2的Action)
public class UserAction {private UserService userService;public UserAction(UserService userService){this.userService = userService;}public void say(){userService.add();}}测试:
public class Test {/** * @param args */public static void main(String[] args) {UserService userService = new UserServiceImpl();UserAction userAction = new UserAction(userService);userAction.say();}}