spring的IOC

来源:互联网 发布:广电网络的wifi网址 编辑:程序博客网 时间:2024/06/03 20:46

提供UserService的接口和实现类

获得UserService实现类的实例

public interface UserService {public void addUser();}public class UserServiceImpl implements UserService {@Overridepublic void addUser() {System.out.println("a_ico add user");}}


若不用spring 直接new一个对象即可

用spring 则将由Spring创建对象实例--> IoC 控制反转(Inverse of  Control)

之后需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中 或者 @Autowired注解


配置文件

 位置:任意,开发中一般在classpath下(src)

 名称:任意,开发中常用applicationContext.xml

 内容:添加schema约束

<?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.xsd"><!-- 配置service <bean> 配置需要创建的对象id :用于之后从spring容器获得实例时使用的class :需要创建实例的全限定类名--><bean id="userService" class="com.lp.a_ioc.UserServiceImpl"></bean></beans>



@Testpublic void demo02(){//从spring容器获得//1 获得容器String xmlPath = "com/lp/a_ioc/beans.xml";ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);//2获得内容 --不需要自己new,都是从spring容器获得UserService userService = (UserService) applicationContext.getBean("userService");userService.addUser();}


基于注解

@Autowiredprivate UserService userService;public void test(){        userService.addUser();}