使用构造器注入实体bean

在学习Spring的Ioc控制反转的时候看到了利用构造器注入实体bean,但是在项目中很少用到,最苦恼就是不知道学到的东西不知道在哪里用,先记录下来。谁能告诉我你们在项目中怎么用,嘎嘎。

 

业务bean

package service;

import java.sql.Savepoint;

import dao.OracleDao;

public class PersonServce {
	
	OracleDao oracleDao ;
	String name;
	//构造器
	public PersonServce(OracleDao oracleDao, String name) {
		super();
		this.oracleDao = oracleDao;
		this.name = name;
	}
	
	
	//打印出来好测试
	public void save() {
		oracleDao.save();
		System.out.println(name);
	}
	
	
	
	
}

 

模拟数据库bean

package dao;

public class OracleDao  {
	
	public static void save() {
		System.out.println("模拟Oracle的保存方法");
	}
	
	
	
}

  配置文件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="oracleDao" class="dao.OracleDao"></bean>
		<!--constructor构造 arg参数 聪明吧嘻嘻-->
                <!--参数是从0开始的,如果是基本类型直接用value属性就可以-->
                <!--如果是自己定义的类型就得把类型写上,引用哪个对象-->
		<bean id="personServce" class="service.PersonServce">
			<constructor-arg index="0" type="dao.OracleDao" ref="oracleDao"></constructor-arg>
			<constructor-arg index="1" value="数据库"></constructor-arg>
		</bean>
          
</beans>

 

测试代码

package test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import service.PersonServce;

public class TestPersonService {


	@Test
	public void test() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
		PersonServce personServce = (PersonServce)applicationContext.getBean("personServce");
		//打印出来模拟数据库的保存和 那个名字,证明注入成功了  嘻嘻
		personServce.save();
	}

}

 

   一开始我以为配置文件ref后面的值必须在前面有声明的,毕竟java是先声明后使用的嘛,后来发现不报错,自以为肯定是spring容器发现ref就去找后面引用的对象,没有实例化就先实例化这个。酷

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值