在学习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就去找后面引用的对象,没有实例化就先实例化这个。