spring ioc核心容器

测试代码

package com.angen;

import org.junit.Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 *
 * @description: TestUserService
 * @date: 2022/7/22
 */
public class TestUserService {
    @Test
    public void test(){
        //1创建spring的核心容器
        //ApplicationContext ac  = new ClassPathXmlApplicationContext("spring.xml");
        ApplicationContext ac  = new ClassPathXmlApplicationContext("classpath:spring.xml");
        //2通过核心容器获取到对象
        UserService userService = (UserService)ac.getBean("userService");
        userService.getName();
    }
}

配置文件

bean标签属性:
    id属性:对象的唯一标识,根据这个标识可以从核心容器中获取到对象
    class:类的全限定名
    scope:表示对象的生命周期 singleton单例(默认) prototype多例
    lazy-init:懒加载,什么时候调用方法的时候才创建对象,默认不是懒加载false
    init-method:配置类的对象初始化的时候调用哪个方法
    destroy-method:配置类的对象销毁时调用哪个方法

    单例模式下(默认没有开启懒加载)
    1,核心容器创建的时候,会创建出配置的所有类的对象
    2,销毁:只有当核心容器被销毁的时候,类的对象才会被销毁
    多例模式下:
    1,当核心容器调用getBean(id)的时候,才会创建对象
    2,多例模式下对象没有放在核心容器里面,对象自己销毁才销毁(垃圾回收机制,没有变量指向堆内存中的对象时)
<?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="userService" class="com.angen.impl.UserServiceImpl">

    </bean>
</beans>

ApplicationContext的三种实现类

ClassPathXmlApplicationContext:从类的根路径下加载配置文件
FileSystemXmlApplicationContext:从磁盘路径上加载配置文件,配置文件可以放在磁盘的任意位置
AnnotationConfigApplicationContext:当我们使用注解配置容器对象时,需要使用此类类创建spring容器,用来读取注解。

实例化Bean的三种方式

无参构造方式实例化Bean

<?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="userService" class="com.angen.impl.UserServiceImpl">

    </bean>
</beans>

静态工厂方式实例化Bean

案例

druid工具类

package com.angen.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtil {
    //定义成员变量
    private static DataSource ds;
    static {
//加载配置文件

        try {
            Properties pro=new Properties();
            pro.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取DataSourse
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    public static void close(Statement sta,Connection conn){
        if(sta!=null){
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            if(conn!=null){
                try {
                    conn.close();//归还连接
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
    public static void close(ResultSet res,Statement sta, Connection conn){
        if(sta!=null){
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();//归还连接
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(res!=null){
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    //获取连接池方法
    public static DataSource getDataSource(){
        return ds;

    }
}

配置文件

driverClassName=com.mysql.cj.jdbc.Driver
#URL连接数据库的URL,其中travel(以下面例子来说)为连接的数据库,后面的参数可不改但不删
url=jdbc:mysql://localhost:3306/travel?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
characterEncoding=utf-8
#安装mysql时候设置的用户与密码
username=root
password=root
#初始化物理连接的个数
initialSize=5
#最大连接池数量
maxActive=10
#获取连接时最大等待时间
maxWait=3000
#用来检测连接是否有效的sql
validationQuery=SELECT 1
#保证安全性!
testWhileIdle=true
<!--
        配置静态工厂实例化Bean
        factory-method:要调用的静态方法名
       
    -->
    <bean id="dataSource" class="com.angen.utils.DruidUtil" factory-method="getDataSource"></bean>

测试

@Test
    public void test2() throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
        DataSource dataSource = (DataSource)applicationContext.getBean("dataSource");
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from dlq_member");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getInt("id"));
            System.out.println(resultSet.getString("username"));
        }
        connection.close();
    }

配置实例工厂实例化Bean

getDataSource1是一个非静态方法

<bean id="druidUtil" class="com.angen.utils.DruidUtil"></bean>
<bean id="dataSource" factory-bean="druidUtil" factory-method="getDataSource1"></bean>

注解方式使用核心容器

首先配置包扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
">
    <!--
        配置包扫描
    -->
    <context:component-scan base-package="com.angen"/>
</beans>

需要配合注解来使用:

1,@Component :如果写value的值,那么默认Bean的id是类的类名的首字母小写

2,@Controller:表现层

3,@Service:Service层的实现类上

4,@Pepository:持久层的实现类上,但是mybatis没有实现类,所以一般不用这个注解


@Scope配置实现类单例或者多例模式

@PostConstruct 类初始化的使用调用

@PreDestroy 单例模式下,容器销毁的时候调用,多例模式下类无变量指向后,被垃圾回收机制回收时调用;


总结:自己写的类使用注解方式进行IOC,框架或者别人写的类,不可以改动的类使用配置文件方式配置。

posted @ 2022-07-22 19:32  在线电影制作人  阅读(5)  评论(0)    收藏  举报  来源