首页 > 其他分享 >Spring Study lesson02 - 案例学习二-23-03-14

Spring Study lesson02 - 案例学习二-23-03-14

时间:2023-03-14 20:35:27浏览次数:42  
标签:xml 03 UserServiceImpl 14 23 dao feijian myService new

把dao中 UserDao的实现类写入到beans.xml中,三个实现类。

<bean id="MySqlDaoImpl" class="com.feijian.dao.MySqlDaoImpl"/>
<bean id="OracleDaoImpl" class="com.feijian.dao.OracleDaoImpl"/>
<bean id="UserDaoImpl" class="com.feijian.dao.UserDaoImpl"/>

把service中的UserServiceImpl写入到beans.xml中

注意 因为在UserServiceImpl 调用了UserDao。所以采用了ref 

<bean id="UserServiceImpl" class="com.feijian.service.UserServiceImpl">
                            <!-- ref   引用Spring容器中创建好的对象
                                 value 具体的值,基本数据类型 -->
    <property name="userDao" ref="OracleDaoImpl"/>

后面在测试中,修改ref对应的三个UserDao实现类名称,即可调用不同的实现类

<?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-2.5.xsd">

    <!--使用Spring来创建对象,在Spring这些都称为Bean
        之前Java
        类型     变量名 = new 类型();
        Hello   hello = new Hello()
        现在Spring
            id = 变量名
         class = new 的对象
       property 相当于给对象中的属性 name 设置一个值  value
        -->
      <bean id="MySqlDaoImpl" class="com.feijian.dao.MySqlDaoImpl"/>
      <bean id="OracleDaoImpl" class="com.feijian.dao.OracleDaoImpl"/>
      <bean id="UserDaoImpl" class="com.feijian.dao.UserDaoImpl"/>

      <bean id="UserServiceImpl" class="com.feijian.service.UserServiceImpl">
                                  <!-- ref   引用Spring容器中创建好的对象
                                       value 具体的值,基本数据类型 -->
          <property name="userDao" ref="OracleDaoImpl"/>
      </bean>
</beans>

测试 (只要修改配置文件中的ref对应的实现类名即可,其他所有的都不需要改动。)

package com.feijian.service;

import com.feijian.dao.MySqlDaoImpl;
import com.feijian.dao.OracleDaoImpl;
import com.feijian.dao.UserDaoImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
//        UserService myService = new UserServiceImpl();
//        ((UserServiceImpl) myService).setUserDao(new OracleDaoImpl());
//        myService.getUser();
//
//        ((UserServiceImpl) myService).setUserDao(new MySqlDaoImpl());
//        myService.getUser();
//
//        ((UserServiceImpl) myService).setUserDao(new UserDaoImpl());
//        myService.getUser();
        //拿到spring 容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //容器在手,天下我有
        UserServiceImpl userServiceImpl =(UserServiceImpl) context.getBean("UserServiceImpl");
        userServiceImpl.getUser();
    }
}

现在程序里什么都不需要修改了,只要修改beans.xml配置文件即可。

标签:xml,03,UserServiceImpl,14,23,dao,feijian,myService,new
From: https://www.cnblogs.com/RUI2022/p/17216239.html

相关文章