Spring4学习(一)IoC控制反转也称为DI依赖注入
程序员文章站
2022-04-07 14:33:41
...
Spring核心配置文件app_core.xml,配置文件路径存放在classpath下面的conf/spring目录下,详细配置
<?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.xsd"> <bean id="groupManagerService" class="org.lian.service.impl.GroupManagerServiceImpl"> <property name="groupManagerDao" ref="groupManagerDao"/> </bean> <bean id="groupManagerDao" class="org.lian.dao.impl.GroupManagerDaoImpl"> </bean> </beans>
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; }
<bean id="groupManagerService" class="org.lian.service.impl.GroupManagerServiceImpl"> <property name="groupManagerDao" ref="groupManagerDao"/> </bean>
与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()); } }
上一篇: 从网约车地方细则看网站SEO优化行业
下一篇: 关键词排名突然下降的原因及相应解决方法