Spring注入方式(一、设值注入)
UserDao:
public interface UserDao { void save(String arg); }
UserDaoImpl:
public class UserDaoImpl implements UserDao { @Override public void save(String arg) { System.out.println("userDaoImpl实现保存:"+arg); } }
UserService:
public interface UserService { void save(String arg); }
UserServiceImpl:编写set方法
public class UserServiceImpl implements UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void save(String arg) { System.out.println("userServiceImpl接受参数:"+arg); arg=arg+":"+this.hashCode(); userDao.save(arg); } }
Bean.xml: 设置设值注入属性
<?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-3.0.xsd"> <bean id="userService" class="test.UserServiceImpl"> <property name="userDao" ref="userDao"/> </bean> <bean id="userDao" class="test.UserDaoImpl"></bean> </beans>
TestMain:测试类
import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { @Test public void test(){ ApplicationContext context= new ClassPathXmlApplicationContext("test/Bean.xml"); UserService say= (UserService) context.getBean("userService"); say.save("123456"); } }
运行结果: