0

I have created RestTemplate Bean in main class and injected this bean in another class of different package by using @Autowired.When I try to use it is null.

Main class: package :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();
    }

    }

package where I have injected 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);

        }
}

When i call this(blockedList) method restTemplate is printing null.Anyone one please help.

ldz
  • 2,217
  • 16
  • 21
nithin
  • 371
  • 9
  • 24

2 Answers2

1

If the CustomFriendList component is not initialized by the Spring mechanism, i.e. because it is created via new CustomFriendList() the RestTemplate member is not autowired and therefore null.

You might want to create a @SpringBootTest, inject the component and then test the functionality.

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {

    @Test
    public void blockedList(CustomFriendList friendList) throws Exception {
        List<String> blocked = friendList.blockedList("testUserId");
        blocked.forEach(System.out::println);
    }

}
ldz
  • 2,217
  • 16
  • 21
0

@Autowired CustomFriendList customFriendList;

Instead of creating new object Autowire bean then its working

nithin
  • 371
  • 9
  • 24