Spring注入方式(二)

Spring注入是指在启动Spring容器加载bean配置的时候,完成对变量的赋值行为
1.设值注入 2.构造注入



InfectionService.java
public interface InfectionService{
  public void save(String arg);

}

InfectionDAO.java

public interface InfectionDAO{
  public void save(String arg);

}
InjectionDAOImpl.java

public class InjectionDAOImpl implements InfectionDAO{
   public void save(String arg){
//模拟数据库保存操作
    System.out.println("保存参数:"+arg");
}

}


InjectionServiceImpl.java

public class InjectionServiceImpl implements InjectionService{
  private InjectionDAO injectionDAO;
  //设值注入setter
 public void setInjectionDAO(InjectionDAO injectionDAO){
  this.injectionDAO =injectionDAO;
}

   public void save(String arg){
//模拟业务操作
    System.out.println("Service接受参数:"+arg");
    arg= arg+ ":"+ this.hashCode();
    injectionDAO.save(arg);
}

}

spring-injection.xml
设值注入

TestInjection.java
import org.junit.Test;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitsTestBase{
   public TestInjection(){
     super("classpath:spring-injection.xml"); //传入配置文件来启动ioc容器
}
@Test
public void testSetter(){
   InjectionService service = super.getBean("injectionService");
   service.save("这是要保存的数据");
}
}







评论

此博客中的热门博文

openflow switch(I)

YANG Tools:YANG to Java Mapping

OpenDaylight架构简介