[我已经在主类中创建了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时,任何人都请帮忙。
如果CustomFriendList
未通过Spring机制初始化,即由于它是通过new CustomFriendList()
创建的,则RestTemplate
成员未自动装配,因此null
。