码迷,mamicode.com
首页 > 编程语言 > 详细

spring基于xml的IOC环境搭建和入门

时间:2019-09-12 13:28:07      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:main   容器   环境   --   pre   依赖   work   cti   path   

配置pom.xml的依赖

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

在resources中创建bean.xml

导入约束

<?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">
</beans>

把对象的创建交给spring来管理

id为获取时的唯一标志,class为要反射的全限定类名

    <!--把对象的创建交给spring管理-->
    <bean id="accountService" class="cn.flypig666.service.impl.AccountServiceImpl"></bean>
    <bean id="accountDao" class="cn.flypig666.dao.impl.AccountDaoImpl"></bean>

使用:

 1 public static void main(String[] args) {
 2 
 3         //1. 获取核心容器对象
 4         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
 5         //2. 根据id获取Bean对象
 6         IAccountService as = (IAccountService) ac.getBean("accountService");
 7         //通过得到IAccountDao的字节码进行强转
 8         IAccountDao ad = ac.getBean("accountDao",IAccountDao.class);
 9         System.out.println(as);
10         System.out.println(ad);
11 
12     }

 

spring基于xml的IOC环境搭建和入门

标签:main   容器   环境   --   pre   依赖   work   cti   path   

原文地址:https://www.cnblogs.com/flypig666/p/11511188.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!