【发布时间】:2020-10-30 09:40:14
【问题描述】:
package com.basicspring.basicapp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean
public Dependency dependency(){
System.out.println("In dependency");
return new Dependency();
}
@Bean
public DependencyContainer dependencyContainer(){
System.out.println("In dependencyContainer");
dependency();
dependency();
dependency();
return new DependencyContainer(dependency());
}
}
输出:
Java HotSpot(TM) 64-Bit Server VM warning: Options -Xverify: none and -no verify were deprecated in JDK 13 and will likely be removed in a future release.
22:00:36.567 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7276c8cd
22:00:36.601 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
22:00:36.759 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
22:00:36.762 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
22:00:36.765 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
22:00:36.766 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
22:00:36.778 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'config'
22:00:36.798 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'dependency'
In dependency
22:00:36.820 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'dependencyContainer'
In dependencyContainer
22:00:36.833 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'spring.liveBeansView.mbeanDomain' in PropertySource 'systemProperties' with value of type String
Process finished with exit code 0
请查看输出中的“Independence”和“IndependencyContainer”语句。即使在dependencyContainer()方法中手动调用了两次dependency()方法后,它也不会被执行两次。
【问题讨论】:
-
因为默认作用域是单例的,所以它得到了一次依赖。
-
你导入依赖类了吗?顺便说一句,您的命名约定很糟糕。
-
嘿,谢谢,我明白你所说的,但我仍然无法理解我手动调用的函数发生了什么
-
@MiroslavTrninic 嘿,感谢您的回复,所有其他类都在同一个包中,并且是公共的
-
注意:做某事“三次”是指做三遍,而不是两次。
标签: java spring spring-boot