Spring-依赖注入之构造器方式注入

版权声明:欢迎大家提出意见,指出错误,互相交流。 https://blog.csdn.net/qq_28796345/article/details/52683633

构造器注入-带有参数的构造函数注入

项目结构如下:

1、新建第一个bean文件

PersonServiceBean.java:

/*
 *@Author swxctx
 *@time 2016年9月27日
 */
package com.sw.servicebean;

public class PersonServiceBean {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

2、新建第二个bean

UserServiceBean.java:

/*
 *@Author swxctx
 *@time 2016年9月27日
 */
package com.sw.servicebean;

import com.sw.service.UserService;

public class UserServiceBean implements UserService {
	/* (non-Javadoc)
	 * @see com.sw.servicebean.UserService#save(com.sw.servicebean.PersonServiceBean)
	 */
	@Override
	public void save(PersonServiceBean person){
		System.out.println(person.getName());
	}
}

3、定义接口(在2之前)

UserService.java:

/*
 *@Author swxctx
 *@time 2016年9月27日
 */
package com.sw.service;

import com.sw.servicebean.PersonServiceBean;

public interface UserService {

	void save(PersonServiceBean person);

}

4、实现注入:、

FirstBean.java:

/*
 *@Author swxctx
 *@time 2016年9月27日
 */
package com.sw.servicebean;

public class FirstBean {
	private PersonServiceBean personServiceBean;
	private UserServiceBean userServiceBean;
	
	public FirstBean(PersonServiceBean personServiceBean,UserServiceBean userServiceBean){
		this.personServiceBean = personServiceBean;
		this.userServiceBean = userServiceBean;
		System.out.println("调用PersonServiceBean与UserServiceBean");
	}
	
	public void save(){
		personServiceBean.setName("xc");
		userServiceBean.save(personServiceBean);
	}
}

5、配置文件

beans.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 -->
    	<bean id="personServiceBean" class="com.sw.servicebean.PersonServiceBean"></bean>
    	<bean id="userServiceBean" class="com.sw.servicebean.UserServiceBean"></bean>
    	<!-- 注入到 firstbean -->
    	<bean id="firstBean" class="com.sw.servicebean.FirstBean">
    		<!-- 创建构造器注入 -->
    		<constructor-arg ref="personServiceBean"></constructor-arg>
    		<constructor-arg ref="userServiceBean"></constructor-arg>	
    	</bean>	
	
</beans>


阅读更多

没有更多推荐了,返回首页