I found a strange behaviour in my Spring App.
The @autowired of an Entity is not working all the time.
I use the Elide project to build an JSONAPI and some custom controllers.
In one controller, one @Autowrited of an entity stays null however it use correctly working when called from Elide.
Controller:
@RestController
public class UploadController {
@Autowired
private ProjectRepository projectRepository;
@PostMapping(value = "/api/projects/{projectId}/upload")
public String uploadItem(@PathVariable long projectId, @RequestParam("file") MultipartFile file,
@RequestParam("projectName") String projectName,
RedirectAttributes redirectAttributes) throws IOException {
Project project = projectRepository.findOneByProjectIdAndName(projectId, projectName);
Integer result = project.getNumberOfItems();
return "";
}
}
Entity
@Setter
@NoArgsConstructor
@Table(name = "projects")
@Entity
@Include(rootLevel = true, type = "projects")
public class Project extends DiffShelfBase {
@Autowired
@Transient
private ItemRepository itemRepository;
@Transient
@ComputedAttribute
public Integer getNumberOfItems() {
return itemRepository.countByProjectId(this.getId());
}
}
Repository
@Repository
@Transactional
public interface ItemRepository extends JpaRepository<Item, Long> {
Integer countByProjectId(long projectId);
}
Configuration
@Configuration
@EnableSpringConfigured
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("http://localhost:4200");
}
};
}
}
I don't understand why but the itemRepository
in null in Project.getNumberOfItems
.