spring以动态的形式来管理对象,注入分为两种:
1. 设置注入:直观 自然
2.构造注入:可以在构造器中决定依赖顺序
以下就是示例:
1.User实体类
package com.domain; import java.io.Serializable; /** * * @author Mr * 实体类 */ public class User implements Serializable { private Integer id; private String uname; private String upwd; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
2.dao实现类,接口省略,因为可以反向生成,就不多拽述了
package com.dao.impl; import com.dao.IUserDao; import com.domain.User; public class IUserDaoImpl implements IUserDao { @Override public void save(User user) { // TODO Auto-generated method stub System.out.println("哇塞,保存用户信息了"); } }
3.biz实现类
package com.biz.impl; import com.biz.IUserBiz; import com.dao.IUserDao; import com.dao.impl.IUserDaoImpl; import com.domain.User; public class IUserBizImpl implements IUserBiz { /* private IUser dao; public IUserBizImpl() { dao = new IUserImpl(); }*/ //上面是以前的方法 private IUserDao dao; public IUserDao getDao() { return dao; } //专业注入 //dao的set访问器,会被spring调用,实现设值注入 public void setDao(IUserDao dao) { this.dao = dao; } @Override public void save(User user) { dao.save(user); } }
4.applicationContext.xml配置文件内容
<bean id="dao" class="com.dao.impl.IUserDaoImpl"></bean> <bean id="biz" class="com.biz.impl.IUserBizImpl"> <!-- 要引用dao --> <property name="dao" ref="dao"></property> </bean> <bean id="logbefore" class="com.aop.LoggerBefore"></bean> <bean id="logafter" class="com.aop.LoggerAfterReturing"></bean>
5.Test测试类
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.biz.IUserBiz; import com.domain.User; /** * * @author Mr * aop测试类 */ public class Test { public static void main(String[] args) { //解析配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); IUserBiz biz = (IUserBiz) ac.getBean("biz"); User users = new User(); users.setUname("adsad"); biz.save(users); } }
6.测试结果,会在控制台打印出来dao接口实现类里的那句话