Spring在应用程序上下文启动时去创建所有的单例bean对象, 而@Lazy注解可以延迟加载bean对象,即在使用时才去初始化.
所以,@Lazy注解, 一是可以减少Spring的IOC容器启动时的加载时间, 二是可以解决bean的循环依赖问题
@Lazy注解用于标识bean是否需要延迟加载.
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
/**
* Whether lazy initialization should occur.
*/
boolean value() default true;
}
查看注解源码可知,只有一个参数, 默认为true, 即添加该注解的bean对象就会延迟初始化.
以SpringBoot环境为例
@Data
@NoArgsConstructor
public class User {
private String name;
private String phone;
private Integer age;
private Person person;
public User(String name, String phone, Integer age) {
System.out.println("我User被初始化了.............");
this.name = name;
this.phone = phone;
this.age = age;
}
}
@Data
@NoArgsConstructor
public class Person {
private String name;
private String phone;
private Integer age;
private User user;
public Person(String name, String phone, Integer age) {
System.out.println("我Person被初始化了.............");
this.name = name;
this.phone = phone;
this.age = age;
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public User createUser() {
return new User("韩宣生", "11111", 24);
}
@Bean
@Lazy
public Person createPerson() {
return new Person("韩立", "11111", 24);
}
}
我User被初始化了.............
我User被初始化了.............
我Person被初始化了.............
@Component
public class PersonConfig {
private UserConfig userConfig;
public PersonConfig( UserConfig userConfig) {
this.userConfig = userConfig;
System.out.println("我是用户配置 PersonConfig");
}
}
@Component
public class UserConfig {
private PersonConfig personConfig;
public UserConfig(PersonConfig personConfig) {
this.personConfig = personConfig;
System.out.println("我是用户配置 UserConfig");
}
}
Description:
The dependencies of some of the beans in the application context form a cycle:
解决办法,给其中一个添加@Lazy注解,如
@Component
public class PersonConfig {
private UserConfig userConfig;
public PersonConfig(@Lazy UserConfig userConfig) {
this.userConfig = userConfig;
System.out.println("我是用户配置 PersonConfig");
}
}
我是用户配置 PersonConfig
我是用户配置 UserConfig
'url' attribute is not specified and no embedded datasource could be configu
解决方法: 是项目没有将application.yml配置文件加载. 点击maven中clean一下项目, 重启项目即可.