Spring4学习(一)IoC控制反转也称为DI依赖注入

阅读更多

        Spring核心配置文件app_core.xml,配置文件路径存放在classpath下面的conf/spring目录下,详细配置




    
         
    

	
    
	

        Java类Service和Dao

public class GroupManagerServiceImpl implements GroupManagerService {

	private GroupManagerDao groupManagerDao;

	/*
	 * public GroupManagerDao getDao() { return groupManagerDao; }
	 * 
	 * public void setDao(GroupManagerDao dao) { groupManagerDao = dao; }
	 */

	/**
	 * 
	 * @description TODO
	 * @return
	 */
	@Override
	public String getGroup() {
		return groupManagerDao.getGroup();
	}

	public GroupManagerDao getGroupManagerDao() {
		return groupManagerDao;
	}

	public void setGroupManagerDao(GroupManagerDao groupManagerDao) {
		this.groupManagerDao = groupManagerDao;
	}

}

 

public class GroupManagerDaoImpl implements GroupManagerDao {

	@Override
	public String getGroup() {
		return "dao.getGroup()";
	}

}

   Spring IoC 配置起来还是比较容易,需要注意的一点是 此例中采用setter注入,这是一种常用的注入方式。bean中set方法名称要和Spring配置文件中bean property标签中name属性保持一致,在此例中

public void setGroupManagerDao(GroupManagerDao groupManagerDao) {
		this.groupManagerDao = groupManagerDao;
	}

 


         
    

 与setter方法的形参名称无关。

        简单 测试IoC的方式

public class App {

	public static void main(String[] args) {
		String classPath = "classpath*:conf/spring/app_*.xml";
		// ApplicationContext context = new ClassPathXmlApplicationContext(
		// new String[] { "services.xml", "daos.xml" });
		ApplicationContext context = new ClassPathXmlApplicationContext(classPath);
		GroupManagerService service = context.getBean(GroupManagerService.class);
		System.out.println(service.getGroup());
	}
}

 

你可能感兴趣的:(Spring4,IoC)