SpringIoc

定义:Spring IoC容器是一个管理Bean的容器,在Spring的定义中,它要求所有的IoC容器都需要实现接口BeanFactory,它是一个顶级容器接口(定义了,按类型或者名称获取Bean的方法)

由于BeanFactory的功能还不够强大,因此Spring在BeanFactory的基础上,还设计了一个更为高级的接口ApplicationContext。它是BeanFactory的子接口之一,

通过注解来加载bean:

AnnotationConfigApplicationContext

两个注解

@Bean:定义一个bean

@**ComponentScan ** bean 扫描路径

扫描特定的包装配 excludeFilters 排除一些不需要的包

@SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.chapter3"}, 
    excludeFilters = {@Filter(classes = Service.class)})

依赖注入

注解@Autowired

根据类型找到对应的Bean,如果对应类型的Bean不是唯一的,那么它会根据其属性名称和Bean的名称进行匹配。如果匹配得上,就会使用该Bean;如果还无法匹配,就会抛出异常。

@Autowired是一个默认必须找到对应Bean的注解(属性/方法)

@Autowired(required = false) // 如果可能找不到

@Primary :相同bean情况下,优先注入

@Primary(“dog”): 按照名称加类型注入,对应BeanFactory接口中的

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

生命周期

它大致分为Bean定义、Bean的初始化、Bean的生存期和Bean的销毁4个部分

Spring Bean的初始化流程:

在这里插入图片描述

延迟初始化

@ComponentScan(basePackages = "com.springboot.chapter3.*", lazyInit = true)

初始化后生命流程

在这里插入图片描述

spring属性文件加载

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

配置属性

database.driverName=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/chapter3
database.username=root
database.password=123456
@Value("${database.driverName}")

@Value注解,既可以加载属性,也可以加在方法上

@ConfigurationProperties("database") 

可以读取特定前缀,根据属性名加载

读取多个文件:

package com.springboot.chapter3.main;
/******** imports ********/
@SpringBootApplication
@ComponentScan(basePackages = {"com.springboot.chapter3"})

@PropertySource(value={"classpath:jdbc.properties"}, ignoreResourceNotFound=true)
public class Chapter3Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter3Application.class, args);
    }
}

@Conditional注解

@Bean(name = "dataSource", destroyMethod = "close")
@Conditional(DatabaseConditional.class)
public DataSource getDataSource(
        @Value("${database.driverName}") String driver,
        @Value("${database.url}") String url,
        @Value("${database.username}") String username, 
        @Value("${database.password}") String password
        ) {
    Properties props = new Properties();
    props.setProperty("driver", driver);
    props.setProperty("url", url);
    props.setProperty("username", username);
    props.setProperty("password", password);
    DataSource dataSource = null;
    try {
        dataSource = BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataSource;
}
package com.springboot.chapter3.condition;
/******** imports ********/
public class DatabaseConditional implements Condition {

    /**
     * 数据库装配条件
     *
     * @param context 条件上下文
     * @param metadata 注释类型的元数据
     * @return true装配Bean,否则不装配
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // 取出环境配置
        Environment env = context.getEnvironment();
        // 判断属性文件是否存在对应的数据库配置
        return env.containsProperty("database.driverName") 
                && env.containsProperty("database.url")
                && env.containsProperty("database.username") 
                && env.containsProperty("database.password");
    }
}

作用域

在这里插入图片描述

生产环境切换

@Profile

@Bean(name = "dataSource", destroyMethod = "close")
@Profile("dev")
public DataSource getDevDataSource() {
    Properties props = new Properties();
    props.setProperty("driver", "com.mysql.jdbc.Driver");
    props.setProperty("url", "jdbc:mysql://localhost:3306/dev_spring_boot");
    props.setProperty("username", "root");
    props.setProperty("password", "123456");
    DataSource dataSource = null;
    try {
        dataSource = BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataSource;
}

@Bean(name = "dataSource", destroyMethod = "close")
@Profile("test")
public DataSource getTestDataSource() {
    Properties props = new Properties();
    props.setProperty("driver", "com.mysql.jdbc.Driver");
    props.setProperty("url", "jdbc:mysql://localhost:3306/test_spring_boot");
    props.setProperty("username", "root");
    props.setProperty("password", "123456");
    DataSource dataSource = null;
    try {
        dataSource = BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataSource;
}

启动时命令

JAVA_OPTS=“-Dspring.profiles.active=dev”

写到配置文件中

application-dev.properties

按照Spring Boot的规则,假设把选项-Dspring.profiles.active配置的值记为{profile},则它会用application-{profile}.properties文件去代替原来默认的application.properties文件

Spring EL

取文件中的值

@Value("${database.driverName}") 
String driver

取其他类的值(支持类方法)

@Value("#{beanName.str}")
private String otherBeanProp = null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值