Spring注解配置实例(2)

import com.springdemo.dao.UserDao; import com.springdemo.entity.User; import com.springdemo.service.UserService; import javax.annotation.Resource; /** * Created by CLY on 2016/12/26. */ public class UserServiceImpl implements UserService{ @Resource(name = "userDao")//使用注解配置,将id为“userDao”的bean注入到“userDaoImpl”里面 private UserDao userDaoImpl;//定义dao层的“接口” public void add(User user) { /* * 将控制器传过来的user对象传给dao层。 * 此处体现的是面向接口编程。好处就是:当该接口的具体实现类改变时,并不需要修改此service中的代码,因为service操作的是接口的方法*/ userDaoImpl.save(user); } } 

Test.java:

import com.springdemo.entity.User; import com.springdemo.service.impl.UserServiceImpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by CLY on 2016/12/26. */ public class Test { //测试UserServiceTest的add方法 public static void main(String args[]){ //创建spring容器,将beans的配置文件装载进容器。 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //通过容器的getBean()方法,获取具体的bean实例(参数是bean的id名)。 UserServiceImpl service = (UserServiceImpl)ctx.getBean("userService"); User u =new User(); u.setName("小明"); u.setAge(18); service.add(u); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0f29a2da4465c1a072edbb6508308179.html