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

spring注入bean两种方式(属性注入,构造器注入)

2015-06-02 10:03 731 查看
利用Spring的IOC实现简单小程序,Spring推荐接口编程,这里定义两个接口:IDao,IService,以及它们的实现类IDaoImpl,IServiceImpl,代码如下:

package DAO;

public interface IDao {
public String sayHello(String name,String sex);

}

package DAO;

public class IDaoImpl implements IDao {
private String c_name;
private int age;

public IDaoImpl(String c_name, int age) {
super();
this.c_name = c_name;
this.age = age;
System.out.println("我叫 " + c_name + "今年"+age+"岁");
}

public String sayHello(String name, String sex) {
return "Hello " + name + sex;
}

}

package service;

public interface IService {

public void service( String name,  String sex);

}

package service;

import DAO.IDao;

public class IServiceImpl implements IService {
IDao dao;

public IDao getDao() {
return dao;
}

public void service(String name, String sex) {
System.out.println(dao.sayHello(name,sex));

}

public void setDao(IDao dao) {
this.dao = dao;
}

}

配置文件applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="daoImpl" class="DAO.IDaoImpl">
<constructor-arg index="1" name="age" value="22"></constructor-arg>
<constructor-arg index="0" name="name" value="Jim"></constructor-arg>
</bean>
<bean id="service" class="service.IServiceImpl">
<property name="dao" ref="daoImpl"></property>
</bean>

</beans>

写一个测试代码的类Test:

package action;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import org.springframework.core.io.ClassPathResource;

import service.IService;

public class Test {
public static void main(String[] args) {
BeanFactory fac = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IService is = (IService) fac.getBean("service");
is.service("Lucy","女士");
}

}

运行代码结果:

我叫 Jim今年22岁

Hello Lucy女士

此例子中用到了spring注入bean的常用两种方式:依赖属性注入(setter方法<property>...</property>),构造器方式注入(<constructor-arg >...<constructor-arg />)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: