@Autowired拒绝在没有@Lazy注释的情况下进行注入

时间:2019-07-23 21:22:02

标签: java spring spring-boot

它说,如果我删除@Lazy注释,我的班级将不会被注入。

SomeClassTest

package com.somePackage;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.somePackage.SomeClass;

@Configuration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath*:junit-spring-context.xml") 
public class SomeClassTestTest {

    @Autowired 
        @Lazy     // If i take this out, the test fails 
    private SomeClass someClass; 

    @Test
    public void someTest() {
        assertNotNull(someClass);
    }   
}

SomeClass

package com.differentPackage;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.DependsOn;

@Service("someClass")
@DependsOn("someOtherClass")
public class SomeClass {
     // Bunch of code here 
}

SomeOtherClass

package com.someOtherPackage.config
import org.springframework.context.annotation.Configuration;

@Configuration
public class SomeOtherClass {
     // Just more code
}

junit-spring-context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
     xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">




    <!-- Detect classes annotated with @Repository, @Component and @Service and register them as beans -->
    <context:component-scan base-package="com.differentPackage" />


</beans>

为什么它只在存在@Lazy的情况下起作用?顺便说一句,SomeClassTest和SomeClass在不同的包中,如果有帮助的话!

1 个答案:

答案 0 :(得分:-1)

Spring(默认情况下)会在应用程序上下文中迅速创建具有单例作用域的所有bean。 那就是Spring框架的思想。对于您的情况,您必须创建一个bean,而不是在应用程序上下文启动时创建,而是在我们请求时创建。这就是强制使用@Lazy的原因。