我有一个Spring @Component
,它作为依赖项添加到另一个类中,并带有注释@Lazy
。根据{{3}},https://www.baeldung.com/spring-lazy-annotation,https://howtodoinjava.com/spring5/core/spring-bean-eager-vs-lazy-init/ @Component
本身应使用@Lazy
进行注释才能正常工作。但是使用以下代码,似乎无需添加@Lazy批注即可起作用。
惰性组件接口。
public interface Lazzy {
public void doSome();
}
惰性组件实现。
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
@Component
// @Lazy // annotation is commented out
public class LazzyImpl implements Lazzy {
private static Logger logger = LogManager.getLogger(LazzyImpl.class);
@PostConstruct
private void init() {
logger.debug("in init");
}
@Override
public void doSome() {
logger.debug("am called");
}
}
亚军类。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/test-context.xml" })
public class LazyTest {
private static Logger logger = LogManager.getLogger(LazyTest.class);
@Autowired
@Lazy
private Lazzy lazzy;
@Test
public void test_Lazy() {
logger.debug("in test_Lazzy");
// lazy.doSome(); // intentionally commented out to check whether LazzyImpl is initialized or not
logger.debug("in test_Lazzy over");
}
}
运行此命令时,会看到以下内容。
LazyTest.test_Lazy(LazyTest.java:25) - in test_Lazzy
LazyTest.test_Lazy(LazyTest.java:27) - in test_Lazzy over
如果在@Lazy
仍被注释掉的情况下在private Lazzy lazzy;
上起飞lazy.doSome();
,我看到了(按预期)。
LazzyImpl.init(LazzyImpl.java:17) - in init
LazyTest.test_Lazy(LazyTest.java:25) - in test_Lazzy
LazyTest.test_Lazy(LazyTest.java:27) - in test_Lazzy over
问题:
为什么在@Lazy
上没有LazzyImpl
注释以及@Component
的情况下,此代码可以正常工作(即,延迟初始化)?
给定的示例使用的是Spring 4.0.3.RELEASE版本。