SpingIOC&DI

Sping

1.入门案例

新建Maven项目

加入依赖

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

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>

编写dao层代码

userDao

public interface UserDao {
    void add();
}

UserDaoImpl

public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("12345");
    }
}

编写配置文件

applicationContext.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">
    <bean id="userDao" class="com.stedu.dao.impl.UserDaoImpl"></bean>

</beans>

通过bean标签,创建相应类型的对象,并将创建的对象交给Spring容器进行管理

默认是通过该类无参的构造方法创建对象,如果没有默认的无参构造方法则会报错

  • id :被创建对象在IOC容器中的标识

  • class: 全类名

  • scoper: 默认值 singleton 单例 生命周期--容器

​ prototype 多例 生命周期--对象

​ WEB项目中: request WEB项目中,Spring创建一个Bean的对象,将对象存入到request域中

​ session WEB项目中,Spring创建一个Bean的对象,将对象存入到session域中

​ global session WEB项目中,应用在Portlet环境,如果没有Portlet环境那么globalSession相当于session

  • init-method : 指定初始化方法

  • destroy-method : 指定销毁的方法

测试类

public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao)context.getBean("userDao");
        userDao.add();
    }
}

2.Bean实例化三种方式

2.1无参构造方法实例化

<bean id="userDao" class="com.stedu.dao.impl.UserDaoImpl"/>
@Test
public void test8() {
    ApplicationContext context = new 	        				                           ClassPathXmlApplicationContext("applicationContext3.xml");
    UserDaoImpl userDao = (UserDaoImpl)context.getBean("userDao");
    userDao.add();

}

2.2工厂静态方法实例化

public class StaticBeanFactory {
    public static UserDao getUserDaoImpl() {
        return new UserDaoImpl();
    }
}
<!-- 静态工厂初始化 -->
<bean id="userDao" class="tech.code2048.factory.StaticBeanFactory" factory-method="getUserDaoImpl"></bean>
//演示通过静态工厂创建Bean
@Test
public void test1() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserDao userDao = (UserDao) context.getBean("userDao");
    userDao.save();
}

2.3工厂实例方法实例化

public class DynamicBeanFactory {
    public UserDao getUserDao() {
        return new UserDaoImpl();
    }
}
<bean id="factory" class="tech.code2048.factory.DynamicBeanFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
//演示通过静态工厂创建Bean
@Test
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserDao userDao = (UserDao) context.getBean("userDao");
    userDao.save();
}

3.依赖注入(Dependency Injection)

指容器负责创建和维护对象之间的依赖关系,而不是通过对象本身负责自己的创建和解决自己的依赖。在当前类需要用到其他类的对象,由Spring为我们提供,我们只需要在配置中说明。

业务层和持久层的依赖关系,在使用 Spring 之后,就让 Spring 来维护了。

简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。

3.1构造方法注入

public interface UserService {
    void add();
}
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserServiceImpl() {
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        userDao.add();
        System.out.println("service add");
    }
}
<bean id="userService" class="com.stedu.service.impl.UserServiceImpl">
    <constructor-arg ref="userDao" name="userDao"/>
</bean>
    @Test
    public void test10() {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext3.xml");
        UserService userService = (UserService)context.getBean("userService");
        userService.add();
    }
}

3.2set方法注入(重点)

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
<bean id="userService" class="UserServiceImpl">
    <!-- set方法注入 -->
    <property name="userDao" ref="userDao"></property>
</bean>

测试方法同上

3.3p名称空间注入

p命名空间注入本质也是set方法注入,但比起上述的set方法注入更加方便,主要体现在配置文件中

1.引入P命名空间

xmlns:p="http://www.springframework.org/schema/p"

2.在Spring配置文件中配置

<!-- p名称空间注入 -->
<bean id="userService" class="tech.code2048.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>

4.依赖注入其他类型

4.1普通数据类型注入

//表示部门的实体类
public class Department {
    private Integer id;//部门编号
    private String name;//部门名称
    private String desc;//部门描述
    
    //set、get方法
    //toString方法
}
<!--
	通过Spring的IOC容器创建Department类的对象,并为其属性注入值
	无参构造方法实例化
-->
<bean id="department" class="tech.code2048.entity.Department">
    <!-- set方法注入
		value:简单类型
	-->
    <property name="id" value="1" />
    <property name="name" value="研发部" />
    <property name="desc" value="项目研发" />
</bean>
@Test
public void test6() {
    //解析配置文件 -- 创建对象 -- 对象交给Spring的IOC容器进行管理
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取Department的对象
    Department department = (Department)context.getBean("department");
    //打印对象
    System.out.println(department);
}

4.2引用类型注入

//表示地址的实体类
public class Address {
    private String province;//省
    private String city;//市
    private String county;//县
    private String street;//街道
    private String no;//门牌号
    
    //set、get
    //toString
}
//表示部门的实体类
public class Department {
    private Integer id;//部门编号
    private String name;//部门名称
    private String desc;//部门描述
    private Address address;//部门地址
    
    //set、get
    //toString
}
<bean id="address" class="tech.code2048.entity.Address">
    <property name="province" value="山东省" />
    <property name="city" value="青岛市" />
    <property name="county" value="市北区" />
    <property name="street" value="龙城路" />
    <property name="no" value="31号" />
</bean>

<!--
	通过Spring的IOC容器创建Department类的对象,并为其属性注入值
	无参构造方法实例化
-->
<bean id="department" class="tech.code2048.entity.Department">
    <!-- set方法注入
		value:简单类型
	-->
    <property name="id" value="1" />
    <property name="name" value="研发部" />
    <property name="desc" value="项目研发" />
    <!-- set方法注入
		ref:引用类型
	-->
    <property name="address" ref="address" />
</bean>

4.3集合数据类型(List)的注入

//表示员工的实体类
public class Employee {
    private Integer id;//员工编号
    private String name;//姓名
    private Integer age;//年龄
    private String gender;//性别
    private List<String> hobby;//爱好
        
    //set、get方法
    //toString方法
}
<!--
	通过Spring的IOC容器创建Employee类的对象,并为其属性注入值
	无参构造方法实例化
-->
<bean id="e1" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="zs" />
    <property name="age" value="30" />
    <property name="gender" value="男" />
    <!--
		集合类型注入
	-->
    <property name="hobby">
        <list>
            <value>学习1</value>
            <value>学习2</value>
            <value>学习3</value>
        </list>
    </property>
</bean>
@Test
public void test7() {
    //解析配置文件 -- 创建对象 -- 对象交给Spring的IOC容器进行管理
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取Employee的对象
    Employee employee = (Employee)context.getBean("e1");
    //打印对象
    System.out.println(employee);
}

4.4集合数据类型(List)的注入

//表示部门的实体类
public class Department {
    private Integer id;//部门编号
    private String name;//部门名称
    private String desc;//部门描述
    private Address address;//部门地址
    private List<Employee> emps;//普通员工
    
    //set、get方法
    //toString方法
}
<bean id="e1" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="zs" />
    <property name="age" value="30" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>学习1</value>
            <value>学习2</value>
            <value>学习3</value>
        </list>
    </property>
</bean>

<bean id="e2" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="ls" />
    <property name="age" value="31" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>爬山</value>
            <value>游泳</value>
            <value>网游</value>
        </list>
    </property>
</bean>
<bean id="department" class="tech.code2048.entity.Department">
    <!-- set方法注入
            value:简单类型
        -->
    <property name="id" value="1" />
    <property name="name" value="研发部" />
    <property name="desc" value="项目研发" />
    <!-- set方法注入
            ref:引用类型
         -->
    <property name="address" ref="address" />
    <property name="emps">
        <list>
            <ref bean="e1" />
            <ref bean="e2" />
        </list>
    </property>
</bean>

4.5集合数据类型(Map<String ,User>)的注入

//表示部门的实体类
public class Department {
    private Integer id;//部门编号
    private String name;//部门名称
    private String desc;//部门描述
    private Address address;//部门地址
    private Map<String, Employee> leader;//部门主管
    private List<Employee> emps;//普通员工
    //set、get
    //toString
}
<bean id="e1" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="zs" />
    <property name="age" value="30" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>学习1</value>
            <value>学习2</value>
            <value>学习3</value>
        </list>
    </property>
</bean>

<bean id="e2" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="ls" />
    <property name="age" value="31" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>爬山</value>
            <value>游泳</value>
            <value>网游</value>
        </list>
    </property>
</bean>

<bean id="e3" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="ww" />
    <property name="age" value="40" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>爬山</value>
            <value>游泳</value>
            <value>网游</value>
        </list>
    </property>
</bean>

<bean id="e4" class="tech.code2048.entity.Employee">
    <property name="id" value="1" />
    <property name="name" value="zl" />
    <property name="age" value="41" />
    <property name="gender" value="男" />
    <!--
            集合类型注入
         -->
    <property name="hobby">
        <list>
            <value>爬山</value>
            <value>游泳</value>
            <value>网游</value>
        </list>
    </property>
</bean>

<bean id="department" class="tech.code2048.entity.Department">
    <!-- set方法注入
            value:简单类型
        -->
    <property name="id" value="1" />
    <property name="name" value="研发部" />
    <property name="desc" value="项目研发" />
    <!-- set方法注入
            ref:引用类型
         -->
    <property name="address" ref="address" />
    <property name="emps">
        <list>
            <ref bean="e1" />
            <ref bean="e2" />
        </list>
    </property>
    <property name="leader">
        <map>
            <entry key="CEO" value-ref="e3" />
            <entry key="CTO" value-ref="e4" />
        </map>
    </property>
</bean>

4.6集合数据类型(Properties)的注入

package tech.code2048.entity;

import java.util.Properties;

public class JdbcConfig {
    private Properties config;

    public Properties getConfig() {
        return config;
    }

    public void setConfig(Properties config) {
        this.config = config;
    }

    @Override
    public String toString() {
        return "JdbcConfig{" +
                "config=" + config +
                '}';
    }
}
<bean id="jdbcConfig" class="tech.code2048.entity.JdbcConfig">
    <!-- Properties类型的注入 -->
    <property name="config">
        <props>
            <prop key="driverName">com.mysql.jdbc.Driver</prop>
            <prop key="url">jdbc:mysql://localhost:3306/test</prop>
            <prop key="username">root</prop>
            <prop key="password">root</prop>
        </props>
    </property>
</bean>
@Test
public void test8() {
    //解析配置文件 -- 创建对象 -- 对象交给Spring的IOC容器进行管理
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取Employee的对象
    JdbcConfig config = (JdbcConfig)context.getBean("jdbcConfig");
    //打印对象
    System.out.println(config);
}

4.7引入其他配置文件

实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,而在Spring主配置文件通过import标签进行加载。

<import resource="applicationContext-xxx.xml"/>
posted @ 2023-07-28 19:50  AaalexQaQ  阅读(27)  评论(0)    收藏  举报