I have a class marked with javax.persistence.Entity
which SpringBoot
says is not a managed type.
The class is as follows
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@Column(unique = true)
private String username;
...
UserRepository.java
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
List<User> findByName(String name);
@Query("UPDATE AppUser u SET u.lastLogin=:lastLogin WHERE u.username = ?#{ principal?.username }")
@Modifying
@Transactional
public void updateLastLogin(@Param("lastLogin") Date lastLogin);
}
AuthenticationSuccessHandler.java
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
@Autowired
private UserRepository userRepository;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
userRepository.updateLastLogin(new Date());
}
}
and SpringSecurityConfig.java
@Configuration
@EnableWebSecurity
@ComponentScan("com.bae.dbauth.security")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private WebApplicationContext applicationContext;
private CustomUserDetailsService userDetailsService;
@Autowired
private AuthenticationSuccessHandlerImpl successHandler;
@Autowired
private DataSource dataSource;
@PostConstruct
public void completeSetup() {
userDetailsService = applicationContext.getBean(CustomUserDetailsService.class);
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder())
.and()
.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.dataSource(dataSource);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login")
.permitAll()
.and()
.formLogin()
.permitAll()
.successHandler(successHandler)
.and()
.csrf()
.disable();
}
....
}
And the application class...
@SpringBootApplication
@PropertySource("classpath:persistence-h2.properties")
@EnableJpaRepositories(basePackages = { "com.bae.dbauth.repositories" })
@EnableWebMvc
@Import(SpringSecurityConfig.class)
public class BaeDbauthApplication implements WebMvcConfigurer {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("driverClassName"));
dataSource.setUrl(env.getProperty("url"));
dataSource.setUsername(env.getProperty("user"));
dataSource.setPassword(env.getProperty("password"));
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
public static void main(String[] args) {
SpringApplication.run(BaeDbauthApplication.class, args);
}
}
When I run the application I get quite long an error message which includes Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.bae.dbauth.model.User
The whole stack trace is quite extensive, it starts with:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springSecurityConfig': Unsatisfied dependency expressed through field 'successHandler'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationSuccessHandlerImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.bae.dbauth.model.User
And I don't understand what is the problem with the User class.
UPDATE: I added/modified annotations in SpringSecurityCongig.java
and tried
@Configuration
@EnableWebSecurity
@ComponentScan({"com.bae.dbauth.security", "com.bae.dbauth.model"})
and
@Configuration
@EnableWebSecurity
@ComponentScan("com.bae.dbauth.security")
@EntityScan(basePackages = {"com.bae.dbauth.model"})
where com.bae.dbauth.model
is package where the User
entity is while com.bae.dbauth
is the package where SpringSecurityConfig.java
and the main application
class are.
The result is the same in each case - the same error message.
The entity is not discovered. If you have your entity manager factoryauto-configured, you have 2 options:
- add @EntityScan
- place your entities in a package that is under your application (these packages are scanned by convention)
I can see that you configure your entity manager factory yourself.
em.setPackagesToScan(new String[] { "com.bae.dbauth.models" });
While your user entity is in: com.bae.dbauth.model
This makes me think this is simply a typo.