[2] Introduction to Spring HelloSpring

3、HelloSpring

ioc inversion of control

Control: Who controls the creation of objects, traditional application objects are created under the control of the program itself, after using spring, the objects are created by spring.

Reversal: The program itself does not create an object, but becomes a passive recipient.

Dependency injection: use the set method for injection.

IOC is a programming idea, from active programming to passive reception.

Up to now, there is no need to modify the program at all. To achieve different operations, you only need to modify the xml configuration file. The so-called ioc can be understood as one sentence: objects are created, managed, and assembled by spring.

Hierarchical relationship:

Insert picture description here

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDaoImpl" class="com.kuber.dao.UserDaoImpl"/>
    <bean id="userDaomethod1Impl" class="com.kuber.dao.UserDaoMethod1Impl"/>
    <bean id="userDaomethod2Impl" class="com.kuber.dao.UserDaoMethod2Impl"/>
    
    <bean id="userServiceImpl" class="com.kuber.service.UserServiceImpl">
        <property name="userDao" ref="userDaoImpl"/>
    </bean>
    <!--
    ref:引用Spring容器中创建好的对象
    value:基本数据类型的具体的值,前面name是基本数据类型的名称
    -->

</beans>

userServiceImpl.java

public class UserServiceImpl implements UserService{
    
    

    private UserDao userDao;

    //利用动态实现值的注入(动态注入)
    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }

    public void getUser() {
    
    
        userDao.getUser();
    }
}

Test case:

@Test
public void spring1(){
    
    
    /*获取ApplicationContext,拿到spring容器*/
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
    userServiceImpl.getUser();


}

effect:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/110251023