Reputation: 5377
I have a Spring Boot application
@SpringBootApplication
public class TaxApplication {
private static final Logger log = LoggerFactory.getLogger(TaxApplication.class);
public static void main(String[] args) {
SpringApplication.run(TaxApplication.class, args);
}
}
I've set it up with Spring JPA for data access
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.show-sql=true
I've set up a JPA Repository for the Account table:
public interface AccountRepository extends JpaRepository<Account, Long> {
List<Account> findByNameStartsWithIgnoreCase(String name);
}
In my MainView, the AccountRepository
doesn't get @Autowired
by the Spring framework,
I can get an instance of it by Constructor injection:
public MainView(AccountRepository accountRepository) {
}
BUT If I try to use Autowiring the Constructor outputs 'null'
@Route
@Configurable
@PageTitle("Basic App Layout")
@CssImport(value = "combobox-styles.css", themeFor="vaadin-combo-box-overlay")
public class MainView extends AppLayout {
@Autowired
AccountRepository accountRepository;
public MainView() {
System.out.println(accountRepository);
}
}
Is this because the code is called from the MainView Constructor? How can we use Autowired JPA beans with Vaadin?
EDIT: I have added @EnableJpaRepositories to the Application, but Autowiring still fails
@SpringBootApplication
@EnableJpaRepositories(basePackages= {"org.mypackage.tax.repo"})
public class TaxApplication {
Upvotes: 0
Views: 508
Reputation: 5352
That's just how autowiring in Spring works.
When you're using constructor injection, you can leave out the @Autowired
annotation as long as there's just one constructor, but it's still autowired.
When you're using fields or setters, the dependencies will be injected after the bean has been constructed. This is unrelated to Vaadin.
Constructor injection is generally preferred over field injection. It makes the class easier to test, since you can easily pass mocks or stubs to the constructor when you instantiate it yourself.
Upvotes: 4
Reputation: 4888
add this to your application TaxApplication:
@EnableJpaRepositories(basePackages= {"com.tax.persistence"})
com.tax.persistence
is the package that contains your repositories.
Also you can annotate MainView with @Component
to make it Spring bean.
Upvotes: 0
Reputation: 856
You can try and add @EnableJpaRepositories
annotation to your TaxApplication
class
Upvotes: 0