Autowired bean在组件类中为null

问题描述 投票:0回答:1

[我已经在主类中创建了RestTemplate Bean,并通过使用@Autowired将该bean注入了另一个不同包的类中。当我尝试使用它时,它为null。

主类:包:com.ff.filter

@ComponentScan(basePackages= {"com.ff"})
@SpringBootApplication
public class CcFilterSearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(CcFilterSearchApplication.class, args);
    }

    @Bean
    @Primary
    RestTemplate restTemplate() {

        return new RestTemplate();
    }

    }

我在其中注入bean的包:com.ff.filter.friendlist

    @Component
    public class CustomFriendList {


        @Autowired
        RestTemplate restTemplate;

        @PostConstruct
        public void init(){
            System.out.println("inti  "+restTemplate);
        }

        public List<String> blockedList(String userId) throws JSONException {

            System.out.println("restTemplate   "+restTemplate);

        }
}

当我调用this(blockedList)方法restTemplate打印null时,任何人都请帮忙。

spring spring-boot spring-mvc dependency-injection
1个回答
0
投票

如果CustomFriendList未通过Spring机制初始化,即由于它是通过new CustomFriendList()创建的,则RestTemplate成员未自动装配,因此null

© www.soinside.com 2019 - 2024. All rights reserved.