Spring注入方式(一、设值注入)

UserDao:

public interface UserDao {
    void save(String arg);
}
View Code

UserDaoImpl:

public class UserDaoImpl implements UserDao {
    @Override
    public void save(String arg) {
        System.out.println("userDaoImpl实现保存:"+arg);
    }
}
View Code

UserService:

public interface UserService {
    void save(String arg);
}
View Code

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);
    }
}
View Code

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>
View Code

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");
    }

}
View Code

运行结果:

posted @ 2019-12-25 15:46  Cool_Yang  阅读(429)  评论(0编辑  收藏  举报