Spring框架——懒惰初始化+@Import

x33g5p2x  于2021-10-07 转载在 Spring  
字(1.6k)|赞(0)|评价(0)|浏览(272)

Spring默认在启动后立即将Bean实例化,可立即使用,要用可以直接拿来用,但是缺点是浪费了资源,占用内存

针对这个问题,Spring提供了懒惰初始化的功能,使用注解@Lazy,可以在需要对象时才初始化对象,不使用的时候就可以不初始化对象,避免浪费。

@Lazy用法

1.与@Component一起用

实现代码

Bean组件

package cn.tedu.demo;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy/*测试懒惰初始化*/
public class Person {
    public Person(){
        System.out.println("创建Person");
    }

    @Override
    public String toString() {
        return "你好";
    }
}

** 测试**

@Test/*测试懒惰初始化*/
    public void testLazy(){
        Person person=a.getBean("person", Person.class);
        System.out.println(person);
        System.out.println("ok");
    }

** 结果**

问题:

** 为什么使用了@Lazy注解还是出现了Person构造器的打印语句??因为使用了Person类**

为什么还会出现其他类的打印语句??因为扫描组件会扫描所有加有@Component注解的类,并出创建实例化对象

如何解决??加@Lazy注解,相当于与@Component注解一起出现

2.与@Bean一起用

测试代码

package cn.tedu.demo;

public class Student {
    public Student(){
        System.out.println("创建Student");
    }

    @Override
    public String toString() {
        return "你好";
    }
}

Config文件

@Bean
    @Lazy
    public Student getStudent(){
        return new Student();
    }

测试

@Test
    public void testLazy2(){
        Student student=a.getBean("getStudent",Student.class);
        System.out.println(student);
        System.out.println("okkk");
    }

@Import注解导入配置

Spring允许创建多个配置类,利用@Import注解可以同时使用多个注解

** 测试代码:**

新建配置文件

package cn.tedu.sys;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class SysConfig {
    @Bean
    public Date getDate(){
        return new Date();
    }
}

主配置文件添加注解

@Import({cn.tedu.sys.SysConfig.class})

测试

@Test/*测试@import*/
    public void testSys(){
        Date date=a.getBean("getDate", Date.class);
        System.out.println(date);
    }

结果

说明@Import注解生效

相关文章

微信公众号

最新文章

更多