I'm trying to make a new X entity, which has a relation to my User entity. When someone is posting a new X entity, im making an "XForm", to validate the results, etc. And if everything is valid, in the "execute" method, i'm trying to find the user from the userRepository based on the id, from the form.
package app.form;
public class XForm {
@Autowired
private UserRepository userRepository;
private long userId;
//[.. other fields + getters and setters]
public X execute() throws Exception {
X myX= new X();
Optional<User> user = userRepository.findById(getUserId());
if (!user.isPresent()) {
throw new Exception("User not found");
}
myX.setUser(user.get());
return myX;
}
And the userRepository is null. I tried to annotate it with @Component, @Service etc, but its still null. And as you can see i'm not trying to make a "new" UserRepository either. Auto wiring the repository works fine everywhere else (In the Controllers, and the Authentication handlers, etc).
Here is the controller:
public ResponseEntity<Object> testNewAction(@RequestBody @Valid XForm form,
BindingResult result) {
try {
if (isValid(result)) {
X myX = form.execute();
XRepository.save(myX);
//return success json
}
//return form errors json
} catch (Exception ex) {
//return exception json
}
}
The base application class look like this, i made sure its scanned too (app.form):
@SpringBootApplication
@ComponentScan(basePackages = {"config", "app"})
@EntityScan(basePackages = {"app.entity"})
@EnableJpaRepositories(basePackages = {"config", "app"})
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.run(args);
}
}
What am i doing wrong?