package com.itheima.service.impl;
import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
/* 常规测试
UserDao dao =new UserDaoImpl();
public void save() {
dao.show();
}*/
/* //spring-context测试 未依赖注入
public void save() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao dao = app.getBean(UserDao.class);
dao.show();
System.out.println(45678);
}*/
/*
依赖注入
UserDao dao;
public void setDao(UserDao dao) {
this.dao = dao;
}
public void save() {
System.out.println(45678);
dao.show();
System.out.println(1234567890);
}*/
@Autowired
UserDao dao;
public void save() {
System.out.println(45678);
dao.show();
System.out.println(1234567890);
}
}
<?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="userDao" class=" com.itheima.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
</bean>-->
<!-- <!–依赖注入–>
<bean id="userDao" class=" com.itheima.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="dao" ref="userDao"></property>
</bean>-->
</beans>
package com.itheima.controller;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
//常规测试
@org.junit.Test
public void test1() {
UserService service = new UserServiceImpl();
service.save();
}
//spring-context测试 未依赖注入
@org.junit.Test
public void test2() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = app.getBean(UserService.class);
service.save();
}
//依赖注入
@org.junit.Test
public void test3() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = app.getBean(UserService.class);
service.save();
}
//注解
@org.junit.Test
public void test4() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = app.getBean(UserService.class);
service.save();
}
}
package com.itheima.dao.impl;
import com.itheima.dao.UserDao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
public void show() {
System.out.println("dao层show方法执行");
}
}
|
|