- 设值注入
示例:
dao层:
public interface InjectionDao { void save(String arg); }
daoImpl层:
public class InjectionDaoImpl implements InjectionDao { @Override public void save(String arg) { System.out.print("保存数据"+arg); } }
service层:
public interface InjectionService { void sava(String arg); }
serviceImpl层:
public class InjectionServiceImpl implements InjectionService { private InjectionDao injectionDao; public void setInjectionDao(InjectionDao injectionDao) { this.injectionDao = injectionDao; } //模拟业务操作 @Override public void sava(String arg) { System.out.print("Service接受参数:"+arg); arg = arg + ";" +this.hashCode(); injectionDao.save(arg); } }
main测试:
@RunWith(BlockJUnit4ClassRunner.class) public class Test extends UnitTestBase{ public TestInjection(){ super("classpath:spring-injection.xml"); } @Test public void testSetter(){ InjectionService is = super.getBean("injectionService"); is.sava("这是要保存的数据"); } @Test public void testCons(){ InjectionService is = super.getBean("injectionService"); is.sava("这是要保存的数据"); } }
spring注入配置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"> <bean id="InjectionService" class="InjectionServiceImpl"> <property name="InjectionDao" ref="InjectionDao"/> </bean> <bean id="InjectionDao" class="InjectionDaoImpl"/> </beans>
测试结果:
Service接受参数:这是要保存的数据
保存数据:这是要保存的数据:912127037