我正在尝试建立一个Spring环境但是我无法正确地注入/自动装配任何东西,因为它总是返回null。
我没有使用任何xml,所以我的配置如下(与web.xml上的Spring无关):
public class SpringConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.scan("br.com.cemiterio");
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
然后使用另一个包调用此类:
@Configuration
@ComponentScan("br.com.xxx")
@EnableTransactionManagement
public class FinanceiroBeanConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException, NamingException {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPersistenceProviderClass(HibernatePersistenceProvider.class);
emf.setPackagesToScan("br.com.xxx.financeiro.model.bean");
emf.setJpaProperties(readJpaProperties());
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return emf;
}
private Properties readJpaProperties() throws IOException {
Properties prop = new Properties();
prop.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
prop.setProperty("hibernate.hbm2ddl.auto", "update");
prop.setProperty("hibernate.show_sql", "false");
prop.setProperty("hibernate.format_sql", "false");
return prop;
}
@Bean
public DataSource dataSource() throws IOException, NamingException {
JndiTemplate template = new JndiTemplate();
return (DataSource) template.lookup("java:comp/env/jdbc/financeiroDS");
}
@Bean
public LoadTimeWeaver loadTimeWeaver() {
return new InstrumentationLoadTimeWeaver();
}
@Bean
public PlatformTransactionManager transactionManager() throws IOException, NamingException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public UsuarioService usuarioService() {
return new UsuarioService();
}
}
我的服务:
@Service
@Transactional
public class UsuarioService {
@PersistenceContext
private EntityManager em;
public Usuario salvar(Usuario usuario) {
return em.merge(usuario);
}
}
现在当我尝试注入它时,它总是为空:
@ManagedBean
@SessionScoped
public class ExemploBean {
private String nome;
@Autowired
private UsuarioService usuarioService;
public void salvar() {
Usuario usuario = new Usuario();
usuario.setNome(nome);
usuarioService.salvar(usuario);
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
我错过了什么吗?