2016-03-05 34 views
0

我使用Vaadin 7,Spring Data JPA 1.9.4.RELEASE和Vaadin-Spring 1.0.0,我有一些DI问题。Vaadin Spring没有启动:依赖注入问题

我选择不使用Spring的引导,因为它会自动做太多的事情,我不能“看”和我所遇到的章若干问题的是花了我太多的时间去了解,并找到原因,所以我宁愿不开机。

我遇到的问题是DI在根用户界面而不是根用户界面的子窗口中工作。

RootUI.java

@SpringUI(path = "/") 
public class RootUI extends UI { 
    @Autowired 
    private EntityManagerFactory entityManagerFactory; // this one works, but I cannot get EntityManager directly 

    @Autowired 
    private ClassService classService; // this one works 


    @Override 
    protected void init(VaadinRequest request) { 
     ... 

     PersonForm form = new PersonForm(); 
     CssLayout layout = new CssLayout(); 
     layout.addComponent(form); 
     Window subWindow = new Window(); 
     subWindow.setContent(layout); 
     ... 
    } 
} 

PersonForm.java

public class PersonForm { 

    @Autowired 
    private ClassService classService; // this doesnot work, 

    public PersonForm(ClassService classService) { 
     classService.findByName();// since the @Autowired dosenot work, I have to pass the one from rootUI. 

    } 

    init() { 
     classService.findByName(); // null exception 
    } 
} 

DBConfig.java

@Configuration 
@EnableVaadin 
@EnableJpaRepositories(basePackages = {"com.example.person.repository"}) 
@EnableTransactionManagement 
public class DBConfig { 
    @Bean 
    public DataSource dataSource() { 
     HikariConfig config = new HikariConfig(); 
     config.setDriverClassName("com.mysql.jdbc.Driver"); 
     config.setJdbcUrl("jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false"); 
     config.setUsername("root"); 
     config.setPassword("root"); 
     config.setMaximumPoolSize(20); 
     HikariDataSource dataSource = new HikariDataSource(config); 
     return dataSource; 
    } 

    @Bean 
    public EntityManagerFactory entityManagerFactory() { 

     HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); 
     vendorAdapter.setGenerateDdl(true); 

     LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); 
     factory.setJpaVendorAdapter(vendorAdapter); 

     factory.setDataSource(dataSource()); 
     factory.setPackagesToScan("com.example.person"); 
     factory.setPersistenceProviderClass(HibernatePersistenceProvider.class); 

     Properties jpaProperties = new Properties(); 
     jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect"); 
     jpaProperties.put("hibernate.hbm2ddl.auto", "update"); 
     factory.setJpaProperties(jpaProperties); 

     factory.afterPropertiesSet(); 
     return factory.getObject(); 
    } 
} 
+0

Spring可以为它管理的组件自动装入字段。如果你实例化这些对象,Spring将不会知道automagic将不会发生。你想要做的是告诉Spring'PersonForm'是它的一个组件,并且从它的初始化上下文中请求一个实例。 – Morfic

回答

0

尝试来注释P ersonForm和一些像@Component一样的Spring注解。或者,最好尝试使用vaadin-spring @SpringView的注释。

+0

'@ Component'应该可以工作,但是我不明白你为什么会尝试使用'@SpringView,毕竟这不是Vaadin视图...但是 – Morfic

+0

@Component是我错过的。谢谢。 –