Java 组件类中的自动连线bean为空
我已经在main类中创建了RESTTemplatebean,并使用@Autowired将该Bean注入到另一个不同包的类中。当我尝试使用它时,它为null 主要类别: 软件包:com.ff.filterJava 组件类中的自动连线bean为空,java,spring,spring-boot,spring-mvc,dependency-injection,Java,Spring,Spring Boot,Spring Mvc,Dependency Injection,我已经在main类中创建了RESTTemplatebean,并使用@Autowired将该Bean注入到另一个不同包的类中。当我尝试使用它时,它为null 主要类别: 软件包:com.ff.filter @ComponentScan(basePackages= {"com.ff"}) @SpringBootApplication public class CcFilterSearchApplication { public static void main(String[] args)
@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);
}
}
@组件
公共类CustomFriendList{
@自动连线
rest模板rest模板;
@施工后
公共void init(){
System.out.println(“inti”+rest模板);
}
公共列表blockedList(字符串userId)抛出JSONException{
System.out.println(“restTemplate”+restTemplate);
}
}
当我调用此(blockedList)方法时,restTemplate正在打印null。任何人都请帮助。如果
CustomFriendList
组件未通过Spring机制初始化,即因为它是通过new CustomFriendList()
创建的,restTemplate
成员未自动连线,因此null
您可能需要一个@springbootest
,注入组件,然后测试功能
@RunWith(SpringRunner.class)
@春靴测试
公共类应用程序测试{
@试验
public void blockedList(CustomFriendList friendList)引发异常{
List blocked=friendList.blockedList(“testUserId”);
blocked.forEach(System.out::println);
}
}
@自动连线
CustomFriendList CustomFriendList
不是创建新对象Autowire bean,而是它的工作以及
@postcontract
打印什么?@Alan Hay在post中构建了它的打印对象,给出的答案很可能是正确的。您正在对新实例而不是Spring托管实例调用该方法。@nithin您是手动调用init
,还是Spring为您调用?我正在通过创建新实例来调用该方法,因此该实例为空。我有@Autowired CustomFriendList,然后它工作。。我有@Autowired CustomFriendList,然后它工作