Spring通过多种方式实现构造依赖注入-----Spring框架



    
    
    
        
        
        
    
    
        
        
        
    
    
        
        
        
    


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">

















package com.powernode.spring6.test;

import com.powernode.spring6.dao.UserDao;
import com.powernode.spring6.service.CustomerService;
import com.powernode.spring6.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDITest
{
    @Test
    public void TestSetDI()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        UserDao userDao = applicationContext.getBean("UserDao", UserDao.class);
        UserService userService = applicationContext.getBean("UserService", UserService.class);
        //set方法注入,是在对象实例化后实现的,构造器注入是对象创建时注入的
        userService.save();
    }
    @Test
    public void TestConstruct()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml");
        CustomerService customerService = applicationContext.getBean("CustomerService", CustomerService.class);
        customerService.save();
        customerService = applicationContext.getBean("CSBean", CustomerService.class);
        customerService.save();
        customerService = applicationContext.getBean("CS",CustomerService.class);
        customerService.save();
    }
}

package com.powernode.spring6.test;

import com.powernode.spring6.dao.UserDao;
import com.powernode.spring6.service.CustomerService;
import com.powernode.spring6.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDITest
{
@Test
public void TestSetDI()
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
UserDao userDao = applicationContext.getBean("UserDao", UserDao.class);
UserService userService = applicationContext.getBean("UserService", UserService.class);
//set方法注入,是在对象实例化后实现的,构造器注入是对象创建时注入的
userService.save();
}
@Test
public void TestConstruct()
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml");
CustomerService customerService = applicationContext.getBean("CustomerService", CustomerService.class);
customerService.save();
customerService = applicationContext.getBean("CSBean", CustomerService.class);
customerService.save();
customerService = applicationContext.getBean("CS",CustomerService.class);
customerService.save();
}
}

你可能感兴趣的:(JAVA随手写,Spring框架,java,算法,开发语言,intellij-idea,数据结构,spring,后端)