title: SPRING BOOT access to entityManager
body: <p>I'm trying to update a project made with spring and hibernate with springboot.</p>
  
  <p>Everything seems ok, but I can't figure how to get the entityManager.</p>
  
  <p>I'm not using spring data, so no domain nor repository is used.</p>
  
  <p>In this project, services are annotated with @service and entityManager is autowire with: @PersistenceContext, </p>
  
  <p>here an example of my service </p>
  
  <pre><code>@Service
  @Transactional
  public class UserServiceImpl implements UserDetailsService, UserService {
  
  @PersistenceContext
  EntityManager entityManager;
  
  
  /**
   * 
   */
  private static final long serialVersionUID = 6384460058124202695L;
  
  public UserDetails loadUserByUsername(String username)
          throws UsernameNotFoundException, DataAccessException {
      User user = entityManager.find(User.class, username);
      return user;
  }
  </code></pre>
  
  <p>The problem here is that the entityManager is null. So I read in doc that if we want to manage the entityManager we have to configure it, so I did this in configuration file:</p>
  
  <pre><code>@Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan(new String[] { "services" });
  
      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());
  
      return em;
  }
  </code></pre>
  
  <p>The application is launching, but still have the entityManager null.</p>
  
  <p>Any clue?</p>
  
  <p>Edit: adding my application class (Has it's a demo project, I put all the config in one file)</p>
  
  <pre><code>@Configuration
  @EnableAutoConfiguration
  @ComponentScan
  @EnableWebMvcSecurity
  public class Application extends WebSecurityConfigurerAdapter{
  
  @Value("${sec.cas.server}")
  private String casServer;
  
  @Value("${sec.app.server}")
  private String appServer;
  
  @Value("${spring.datasource.driverClassName}")
  private String databaseDriverClassName;
  
  @Value("${spring.datasource.url}")
  private String databaseUrl;
  
  @Value("${spring.datasource.username}")
  private String databaseUsername;
  
  @Value("${spring.datasource.password}")
  private String databasePassword;
  
  public static void main(String[] args) {
      ApplicationContext ctx = SpringApplication.run(Application.class, args);
  
      System.out.println("Let's inspect the beans provided by Spring Boot:");
  
      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
          System.out.println(beanName);
      }
  }
  
  @Bean
  public ComboPooledDataSource dataSource() {
      ComboPooledDataSource datasource = new ComboPooledDataSource();
      try {
          datasource.setDriverClass(databaseDriverClassName);
      } catch (PropertyVetoException e) {
          throw new IllegalArgumentException("Wrong driver class");
      }
      datasource.setJdbcUrl(databaseUrl);
      datasource.setUser(databaseUsername);
      datasource.setPassword(databasePassword);
  
      datasource.setAcquireIncrement(1);
      datasource.setIdleConnectionTestPeriod(600);
      datasource.setMaxPoolSize(500);
      datasource.setMinPoolSize(50);
      datasource.setMaxStatements(0);
  
      datasource.setMaxConnectionAge(600);
      datasource.setMaxIdleTime(600);
  
      return datasource;
  }
  
  
  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
      DefaultPersistenceUnitManager  unitManager = new DefaultPersistenceUnitManager ();
      unitManager.setDefaultDataSource(dataSource());
      unitManager.setPersistenceXmlLocations("classpath*:META-INF/persistence.xml"); //location of     your persistence.xml file
      unitManager.setPackagesToScan(new String[] { "services" });
      unitManager.setDefaultPersistenceUnitName("entityManager");
  
     LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
     em.setPersistenceUnitManager(unitManager);
  
     JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
     em.setJpaVendorAdapter(vendorAdapter);
     em.setJpaProperties(additionalProperties());
  
     return em;
  }
  
  Properties additionalProperties() {
      Properties properties = new Properties();
      properties.setProperty("hibernate.show_sql", "false");
      properties.setProperty("hibernate.format_sql", "true");
      properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle9iDialect");
      return properties;
   }
  
      @Bean
      public JdbcDaoImpl jdbcUserService() {
          JdbcDaoImpl jdbcDaoImpl = new JdbcDaoImpl();
          jdbcDaoImpl.setEnableGroups(true);
          jdbcDaoImpl.setEnableAuthorities(true);
          jdbcDaoImpl.setDataSource(dataSource());
          return jdbcDaoImpl;
      }
  
      @Bean
      public ServiceProperties serviceProperties() {
          ServiceProperties serviceProperties = new ServiceProperties();
          serviceProperties.setService("http://"+appServer+"/j_spring_cas_security_check");
          serviceProperties.setSendRenew(false);
          return serviceProperties;
      }
  
      @Bean
      public CasAuthenticationProvider casAuthenticationProvider() {
          CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
             casAuthenticationProvider.setAuthenticationUserDetailsService(authenticationUserDetailsService());
          casAuthenticationProvider.setUserDetailsService(new UserServiceImpl());
          //casAuthenticationProvider.setAuthenticationUserDetailsService(userServiceImpl.class);
          casAuthenticationProvider.setServiceProperties(serviceProperties());
          casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
          casAuthenticationProvider.setKey("an_id_for_this_auth_provider_only");
          return casAuthenticationProvider;
      }
  
      @Bean
      public UserDetailsByNameServiceWrapper authenticationUserDetailsService() {
          UserDetailsByNameServiceWrapper userDetailsByName = new UserDetailsByNameServiceWrapper();
          userDetailsByName.setUserDetailsService(jdbcUserService());
          return userDetailsByName;
      }
  
      @Bean
      public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
          Cas20ServiceTicketValidator casServiceTicketValidator = new Cas20ServiceTicketValidator("https://"+casServer+"/cas");
          casServiceTicketValidator.setProxyCallbackUrl("http://"+appServer+"/");
          casServiceTicketValidator.setProxyGrantingTicketStorage(new ProxyGrantingTicketStorageImpl());
          return casServiceTicketValidator;
      }
  
      @Bean
      public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
          CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
          casAuthenticationFilter.setAuthenticationManager(authenticationManager());
          casAuthenticationFilter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
          casAuthenticationFilter.setProxyGrantingTicketStorage(new ProxyGrantingTicketStorageImpl());
          casAuthenticationFilter.setProxyReceptorUrl("/secure/receptor");
          return casAuthenticationFilter;
      }
  
      @Bean
      public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
          CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint();
          casAuthenticationEntryPoint.setLoginUrl("https://"+casServer+"/cas/login");
          casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
          return casAuthenticationEntryPoint;
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .addFilter(casAuthenticationFilter());
          http
              .exceptionHandling()
                  .authenticationEntryPoint(casAuthenticationEntryPoint());
          http
          .authorizeRequests()
              .antMatchers("/", "/home").authenticated()
              .anyRequest().authenticated();
      }
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth
              .authenticationProvider(casAuthenticationProvider());
      }
  </code></pre>