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

配置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 学习(二)


下一篇:在spring中直接在类中注入dao