How do I mock an autowired @Value field in Spring with Mockito?

I’m using Spring 3.1.4.RELEASE and Mockito 1.9.5. In my Spring class I have: @Value(“#{myProps[‘default.url’]}”) private String defaultUrl; @Value(“#{myProps[‘default.password’]}”) private String defaultrPassword; // … From my JUnit test, which I currently have set up like so: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ “classpath:test-context.xml” }) public class MyTest { I would like to mock a value for my “defaultUrl” field. Note … Read more

intellij incorrectly saying no beans of type found for autowired repository

I have created a simple unit test but IntelliJ is incorrectly highlighting it red. marking it as an error No beans? As you can see below it passes the test? So it must be Autowired? 43 Answers 43 I had this same issue when creating a Spring Boot application using their @SpringBootApplication annotation. This annotation … Read more

What exactly is Field Injection and how to avoid it?

I read in some posts about Spring MVC and Portlets that field injection is not recommended. As I understand it, field injection is when you inject a Bean with @Autowired like this: @Component public class MyComponent { @Autowired private Cart cart; } During my research I also read about constructor injection: @Component public class MyComponent … Read more

Spring @Autowire on Properties vs Constructor

So since I’ve been using Spring, if I were to write a service that had dependencies I would do the following: @Component public class SomeService { @Autowired private SomeOtherService someOtherService; } I have now run across code that uses another convention to achieve the same goal @Component public class SomeService { private final SomeOtherService someOtherService; … Read more

Understanding Spring @Autowired usage

I am reading the spring 3.0.x reference documentation to understand Spring Autowired annotation: 3.9.2 @Autowired and @Inject I am not able to understand the below examples. Do we need to do something in the XML for it to work? EXAMPLE 1 public class SimpleMovieLister { private MovieFinder movieFinder; @Autowired public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder … Read more

How does autowiring work in Spring?

I’m a little confused as to how the inversion of control (IoC) works in Spring. Say I have a service class called UserServiceImpl that implements UserService interface. How would this be @Autowired? And in my Controllers, how would I instantiate an instance of this service? Would I just do the following? UserService userService = new … Read more

Why is my Spring @Autowired field null?

Note: This is intended to be a canonical answer for a common problem. I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get … Read more