spring ioc

spring ioc主要用到了工厂设计模式和反射的技术,在spring中定义的类型统称为bean,创建bean的工厂是BeanFactory,ApplicationContext是BeanFactory的子接口,是我们常用的类型,这个接口有三个实现分别是

ClassPathXmlApplicationConext:直接在src根目录查找XML配置文件

FileSystemXmlApplicationConext:通过制定XML配置文件的绝对路径来加载配置文件

ContextLoaderListener:在web服务器中自动加载配置文件

附demo

public static void main(String[] args) {
        ApplicationContext context= new ClassPathXmlApplicationContext("application.xml");
        
        TestDao dao= (TestDao)context.getBean("test");
        dao.sayHello();
    }

    public static void main(String[] args) {
        ApplicationContext context= new FileSystemXmlApplicationContext("D:\\spring-workspace\\demo1\\src\\main\\java\\application.xml");
        TestDao dao= (TestDao)context.getBean("test");
        dao.sayHello();
    }

ContextLoaderListener使用需要在web.xml中进行配置,web.xml通常在webapp/WEB-INF/文件夹下

<servlet>
        <servlet-name>springmvc01</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

ApplicationContext applicationContext = (WebApplicationContext) request.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        DemoService service = (DemoService) applicationContext.getBean("demoServiceImpl");
        service.sayHello();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值