Spring核心之IOC(Inversion of Control)控制反转的三种实现方式

总结一下Spring框架核心之IOC(Inversion of Control)控制反转的三种实现方式:
1、纯配置文件配置; 2、配置文件+注解两掺; 3、纯注解;
其中,个人认为:纯配置文件配置的方式易读易理解;纯注解方式开发效率更高;配置文件+注解两掺方式在实际应用中更常用。

此文中IOC的三种实现方式均采用maven工程环境搭建。

maven工程导入依赖坐标

	
        5.0.5.RELEASE
    
    
    
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            junit
            junit
            4.12
        
    

1. 纯配置文件配置
Spring配置文件applicationContext.xml中主要配置

	
    
    
    
        
        
    

dao层主要代码

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println(" save running .... ");
    }
}

service层主要代码

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void save() {
        userDao.save();
    }
}

测试类主要代码

public class SpringTest {
    @Test
    public void test() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.save();
    }
}

2. xml配置+注解两掺
Spring配置文件applicationContext.xml中主要配置



dao层主要代码

@Repository
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println(" save running .... ");
    }
}

service层主要代码

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    public void save() {
        userDao.save();
    }
}

测试类主要代码

public class SpringTest {
    @Test
    public void test() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.save();
    }
}

3. 纯注解
配置类

@Configuration
@ComponentScan("xxx.xxx")
public class SpringConfig {
}

dao层主要代码

@Repository
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println(" save running .... ");
    }
}

service层主要代码

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    public void save() {
        userDao.save();
    }
}

测试类主要代码

public class SpringTest {
    @Test
    public void test() {
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = (UserService) ac.getBean("userService");
        userService.save();
    }
}

如文中有不合理之处,请各位批评指正。

你可能感兴趣的:(Java,Spring,DI,IOC)