I am getting below error in console when i am trying to run spring boot app.I am new to spring boot and learning everything newly but i am stuck.I did go through various stackoverflow answers but none resolved the issue
Error log
[2m2023-01-20T22:56:15.534+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.EnfamilrestapiSpringrestapiApplication[0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-01-20T22:56:17.467+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2023-01-20T22:56:17.504+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardService [0;39m [2m:[0;39m Starting service [Tomcat]
[2m2023-01-20T22:56:17.505+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardEngine [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/10.1.4]
[2m2023-01-20T22:56:17.744+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2023-01-20T22:56:17.746+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 2106 ms
[2m2023-01-20T22:56:17.878+05:30[0;39m [33m WARN[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mConfigServletWebServerApplicationContext[0;39m [2m:[0;39m Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'enfamilController': Unsatisfied dependency expressed through field 'repo': No qualifying bean of type 'com.nischitha.springweb.repository.EnfamilRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
[2m2023-01-20T22:56:17.884+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardService [0;39m [2m:[0;39m Stopping service [Tomcat]
[2m2023-01-20T22:56:18.150+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36m.s.b.a.l.ConditionEvaluationReportLogger[0;39m [2m:[0;39m
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
[2m2023-01-20T22:56:18.203+05:30[0;39m [31mERROR[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field repo in com.nischitha.springweb.controller.EnfamilController required a bean of type 'com.nischitha.springweb.repository.EnfamilRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.nischitha.springweb.repository.EnfamilRepository' in your configuration.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nischitha.springweb</groupId>
<artifactId>enfamilrestapi_springrestapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>enfamilrestapi_springrestapi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Enfamil(entity)
package com.nischitha.springweb.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
#Entity
public class Enfamil {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public Enfamil() {
}
#Override
public String toString() {
return "Enfamil [id=" + id + ", name=" + name + ", price=" + price + ", description=" + description + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String name;
private String price;
private String description;
}
**EnfamilRepository **
package com.nischitha.springweb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.nischitha.springweb.entity.Enfamil;
#Repository
public interface EnfamilRepository extends JpaRepository<Enfamil, Integer> {
}
Enfamil Controller
package com.nischitha.springweb.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.nischitha.springweb.entity.Enfamil;
import com.nischitha.springweb.repository.EnfamilRepository;
#RestController
public class EnfamilController {
#Autowired
EnfamilRepository repo;
#RequestMapping(value = "/enfamil/", method = RequestMethod.GET)
public List<Enfamil> findProducts() {
return repo.findAll();
}
#RequestMapping(value = "/enfamil/{id}", method = RequestMethod.GET)
public Enfamil getProduct(#PathVariable("id") int id) {
return repo.findById(id).get();
}
#RequestMapping(value = "/enfamil/", method = RequestMethod.POST)
public Enfamil createProduct(#RequestBody Enfamil enfamil) {
return repo.save(enfamil);
}
#RequestMapping(value = "/enfamil/", method = RequestMethod.PUT)
public Enfamil updateProduct(Enfamil enfamil) {
return repo.save(enfamil);
}
#RequestMapping(value = "/enfamil/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable("id") int id) {
repo.deleteById(id);
}
}
**
EnfamilrestapiSpringrestapiApplication.java**
package com.nischitha.springweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class EnfamilrestapiSpringrestapiApplication {
public static void main(String[] args) {
SpringApplication.run(EnfamilrestapiSpringrestapiApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql//localhost:3306/mydb
spring.datasource.username=
spring.datsource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Folder Structure screenshot
Below are the things i tried-
putting all files in one folder
2.marking repository bean as #NoRepositoryBean
3.#EnableJpaRepositories(basePackages = "com.nischitha.springweb.repository") - added this to EnfamilrestapiSpringrestapiApplication.java file
Related
I am getting unauthorized error even for permit all URLs.
This is my security config file:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Value("${auth0.audience}")
private String audience;
#Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;
#Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuer);
OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
jwtDecoder.setJwtValidator(withAudience);
return jwtDecoder;
}
#Bean
public DefaultSecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth-> auth
.requestMatchers("/api/public/**","/login","/register").permitAll().anyRequest().authenticated())
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
This is my validator file:
class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private final String audience;
AudienceValidator(String audience) {
this.audience = audience;
}
public OAuth2TokenValidatorResult validate(Jwt jwt) {
OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
if (jwt.getAudience().contains(audience)) {
return OAuth2TokenValidatorResult.success();
}
return OAuth2TokenValidatorResult.failure(error);
}
}
And these are the Log files
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m [2m (v3.0.1)[0;39m
[2m2023-02-19T22:23:00.142+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mc.r.apigateway.ApiGatewayApplication [0;39m [2m:[0;39m Starting ApiGatewayApplication using Java 17.0.6 with PID 16708 (C:\PM\api-gateway - Copy\target\classes started by KrishnaGopikaUrlagan in C:\PM\api-gateway - Copy)
[2m2023-02-19T22:23:00.142+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mc.r.apigateway.ApiGatewayApplication [0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-02-19T22:23:00.669+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.cloud.context.scope.GenericScope [0;39m [2m:[0;39m BeanFactory id=54aac986-e0d5-38c2-b07e-9736a12b46b1
[2m2023-02-19T22:23:01.470+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.471+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.471+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'reactorDeferringLoadBalancerExchangeFilterFunction' of type [org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.538+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mswordEncoderAuthenticationManagerBuilder[0;39m [2m:[0;39m No authenticationProviders and no parentAuthenticationManager defined. Returning null.
[2m2023-02-19T22:23:02.904+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.s.web.DefaultSecurityFilterChain [0;39m [2m:[0;39m Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#5c9f1e10, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#9658b45, org.springframework.security.web.context.SecurityContextHolderFilter#291e1f26, org.springframework.security.web.header.HeaderWriterFilter#1d58f1b7, org.springframework.security.web.authentication.logout.LogoutFilter#2de04a13, org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter#738072a1, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#240b8e76, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#2ed115b5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#2c68f8e0, org.springframework.security.web.access.ExceptionTranslationFilter#4f68b71d, org.springframework.security.web.access.intercept.AuthorizationFilter#733ad243]
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/logout', method=POST}
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mathPatternParserServerWebExchangeMatcher[0;39m [2m:[0;39m Request 'GET /api/public/allergy' doesn't match 'POST /logout'
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m No matches found
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36ma.DelegatingReactiveAuthorizationManager[0;39m [2m:[0;39m Checking authorization on '/api/public/allergy' using org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager#69b0d355
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mebSessionServerSecurityContextRepository[0;39m [2m:[0;39m No SecurityContext found in WebSession: 'org.springframework.web.server.session.InMemoryWebSessionStore$InMemoryWebSession#2da15e91'
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.a.AuthorizationWebFilter [0;39m [2m:[0;39m Authorization failed: Access Denied
This the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>api-gateway-auth0</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2022.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>netflix-candidates</id>
<name>Netflix Candidates</name>
<url>https://artifactory-oss.prod.netflix.net/artifactory/maven-oss-candidates</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
I tried to permit all public URLs and authenticate all the private URLs. but even though I permitted the public URLs I am getting a 401 error. I took out the webflux dependency, added the #Configuration annotation and made some more changes based on the suggestions I got from the comments. But still, the same problem.
Please help me solve this error.
Spring Security 6 is deny-by-default, so if you don't explicitly reference a URL, or provide a wildcard, it'll deny access. Try this:
.requestMatchers("api/public/**").permitAll())
The reference you are providing is a specific one. You need to provide a general one for spring security to either accept or reject apis that belong to that path. Try the below:
instead of "api/public" or api/private use "api/public/*" and "api/private/*"
If you are using Spring Security 6.x, you may be missing an #Configuration on your SecurityConfig. I added a comment explaining the discrepancy between your logs and your config, so if the missing annotation is your problem, you may face further configuration issues afterwards.
See the 5.8 migration guide (which should be used when upgrading to 6.0) for more info.
Edit:
Upon discussing further in comments and reviewing your updated question, it appears that you are building an application using spring-boot-starter-gateway (Spring Cloud Gateway), which builds on Spring WebFlux and requires a corresponding security configuration using #EnableWebFluxSecurity. Explicit WebFlux Security Configuration in the reference contains an example configuration to get you started with Spring WebFlux.
I try to secure my spring boot application using security and mysql as provider.
When I debug application I get this error:
Field sysUserRepository in SysUserService required a bean named 'entityManagerFactory' that could not be found.
I already read this question
How to use Spring Boot with MySQL database and JPA?
This is SysUserService
package com.cm.sb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cm.sb.model.SysUser;
import com.cm.sb.repository.SysUserRepository;
#Service
public class SysUserService {
#Autowired
SysUserRepository sysUserRepository;
public SysUser findByusername(String username) {
return sysUserRepository.findByUsername(username);
}
}
This is my spring boot initializer
package com.cm.sb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(scanBasePackages={"com.cm.sb"},exclude = { SecurityAutoConfiguration.class })
#EnableJpaRepositories(basePackages = "com.cm.sb")
public class SbApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SbApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SbApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/sb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=none
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
security.user.password=ciro
security.user.username=ciro
This is my secure config class
package com.cm.sb.config;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userDetailService")
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
.and().authorizeRequests().antMatchers("/dashboard").hasRole("USER")
.and().authorizeRequests().antMatchers("/home").permitAll()
.and().formLogin().defaultSuccessUrl("/dashboard").loginPage("/login")
.and().logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
}
}
This is My repository class
package com.cm.sb.repository;
import com.cm.sb.model.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository("sysUserRepository")
public interface SysUserRepository extends JpaRepository<SysUser, Integer> {
SysUser findByUsername(String username);
}
edit: my pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cm</groupId>
<artifactId>sb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sb</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<hibernate.version>4.3.11.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- necessaria per le jsp -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I tried to use the same code that you have posted before and i can start the service boot.
Here is all what i change :
package com.cm.sb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.cm.sb.entity.SysUser;
public interface SysUserRepository extends JpaRepository<SysUser, Integer> {
SysUser findByUsername(String username);
}
The main class :
package com.cm.sb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
#EnableJpaRepositories(basePackages = "com.cm.sb.repository")
#ComponentScan("com.cm.sb.service")
#EntityScan("com.cm.sb.entity")
public class SbExampleApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SbExampleApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SbExampleApplication.class, args);
}
}
The properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/sb
spring.datasource.username=root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create // because i want to generate the db from entities
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
security.user.password=ciro
security.user.username=ciro
The stack trace :
2018-11-29 18:19:17.746 INFO 6340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-29 18:19:17.802 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.802 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:17.862 INFO 6340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-29 18:19:18.161 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-29 18:19:18.163 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-11-29 18:19:18.171 INFO 6340 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-11-29 18:19:18.257 INFO 6340 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-29 18:19:18.260 INFO 6340 --- [ main] com.cm.sb.SbExampleApplication : Started SbExampleApplication in 5.051 seconds (JVM running for 5.991)
2018-06-04 16:55:38.821 WARN 10092 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicController': Unsatisfied dependency expressed through field 'topicService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicService': Unsatisfied dependency expressed through field 'topicRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicRepository': Cannot create inner bean '(inner bean)#77e80a5e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#77e80a5e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-06-04 16:55:38.840 INFO 10092 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-06-04 16:55:38.884 INFO 10092 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-04 16:55:39.082 ERROR 10092 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in com.example.demo.topic.TopicService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
here is my Entity Class
package com.example.demo.topic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Topic")
public class TopicPOJO {
#Id
#Column(name = "Id", nullable = false)
String id;
#Column(name = "name", nullable = true)
String name;
#Column(name = "desc", nullable = true)
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public TopicPOJO(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public TopicPOJO() {
super();
}
}
**here is my application**
package com.example.demo.topic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoJpaApplication {
public static void main(String[] args) {
SpringApplication.run(DemoJpaApplication.class, args);
}
}
Here is My POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-JPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-JPA</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
here is my interface which extends repository
package com.example.demo.topic;
import org.springframework.data.repository.CrudRepository;
public interface TopicRepository extends CrudRepository<TopicPOJO,String>
{
}
here is my service class
package com.example.demo.topic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
#Service
public class TopicService {
#Autowired
TopicRepository topicRepository;
public List<TopicPOJO> getAllTopics()
{
List<TopicPOJO> topics=new ArrayList<>();
topicRepository.findAll()
.forEach(topics::add);
return topics;
}
public TopicPOJO getTopic(String id)
{
return topicRepository.findById(id).get();
}
public void addTopic(TopicPOJO topic)
{
topicRepository.save(topic);
}
public void updateTopic(String id,TopicPOJO topic) {
topicRepository.save(topic);
}
public void deleteTopic(String id) {
topicRepository.deleteById(id);
}
}
Here is my Controller
package com.example.demo.topic;
import java.util.List;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TopicController {
#Autowired
TopicService topicService;
#RequestMapping("/topic")
public List<TopicPOJO> getAlltopics()
{
return topicService.getAllTopics();
}
#RequestMapping("/topic/{id}")
public TopicPOJO gettopic(#PathVariable String id)
{
return topicService.getTopic(id);
}
#RequestMapping(method=RequestMethod.POST,value="/topic")
public void addTopic(#RequestBody TopicPOJO topic)
{
topicService.addTopic(topic);
}
#RequestMapping(method=RequestMethod.PUT,value="/topic/{id}")
public void updateTopic(#RequestBody TopicPOJO topic,#PathVariable String
id)
{
topicService.updateTopic(id,topic);
}
#RequestMapping(method=RequestMethod.DELETE,value="/topic/{id}")
public void deleteTopic(#PathVariable String id)
{
topicService.deleteTopic(id);
}
}
guys i've met up with a problem when i import the code from my instructor , on his machine it is well,but on my machine it crashes. Here comes the code and the configfile and error logs. thank you in advance.
this is the entity class, through my understanding , there will be no mistake in this area, cause the error log focused on the datasources area.
package com.imooc.domain;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* Created by 廖师兄
* 2016-11-03 23:07
*/
#Entity
public class Girl {
#Id
#GeneratedValue
private Integer id;
#NotBlank(message = "这个字段必传")
private String cupSize;
#Min(value = 18, message = "未成年少女禁止入门")
// #NotNull
// #Max()
// #Length()
private Integer age;
#NotNull(message = "金额必传")
private Double money;
public Girl() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
#Override
public String toString() {
return "Girl{" +
"id=" + id +
", cupSize='" + cupSize + '\'' +
", age=" + age +
", money=" + money +
'}';
}
}
below is my pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.imooc</groupId>
<artifactId>girl</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>girl</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
below is my application.yum file, as the reason that i used intellij idea ,so the key word is not likely to be wrong. Here goes the application.yml file.
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
last and the most important is the log. It shows like this.
2017-10-06 10:38:20.687 WARN 395992 --- [ main]
ationConfigEmbeddedWebApplicationContext : Exception encountered during
context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ***'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource*** [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2017-10-06 10:38:20.687 INFO 395992 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-10-06 10:38:20.703 WARN 395992 --- [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
java.lang.Object.wait(Native Method)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
2017-10-06 10:38:20.703 INFO 395992 --- [ main] utoConfigurationReportLoggingInitializer :
`
I am trying to connect backend and frontend two separate projects of eclipse spring maven. I have added dependency to do so. But when I write down validate credentials logic in Homecontroller.java, after running on server its showing this exception. Please help to resolve it I have tried many methods already please suggest.
HomeController.java
package com.yogesh.shoponlinefrontend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Controller
public class HomeController {
#Autowired
UserDAO userDAO;
#RequestMapping("/")
public String homePage() {
System.out.println("Executing the method homePage");
return "home";
}
#RequestMapping("/login")
public ModelAndView showLoginPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked login link");
mv.addObject("showLoginPage", "true");
return mv;
}
#RequestMapping("/register")
public ModelAndView showRegistrationPage() {
ModelAndView mv = new ModelAndView("home");
mv.addObject("msg", "You clicked Registration link ");
mv.addObject("showRegistrationPage", "true");
return mv;
}
#RequestMapping("/validate")
public ModelAndView validate(#RequestParam("id") String id, #RequestParam("password") String pwd) {
System.out.println("In validate method");
System.out.println("id: " + id);
System.out.println("pwd: " + pwd);
ModelAndView mv = new ModelAndView("home");
if (userDAO.validate(id, pwd) != null) {
mv.addObject("successMsg", "You logged in successfully");
} else {
mv.addObject("errorMsg", "Invalid Credentials..Please try again");
}
return mv;
}
}
UserDAO.java
package com.yogesh.shoponlineback.dao;
import java.util.List;
import com.yogesh.shoponlineback.model.User;
public interface UserDAO {
public List<User> list();
public User get(String username);
public User validate(String username, String password);
public boolean save(User user);
public boolean update(User user);
}
User.java
package com.yogesh.shoponlineback.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Entity
//cha
#Table(name="USER")
#Component
public class User {
#Id
private String username;
#NotEmpty(message = "please enter your name")
private String name;
#Min(5)
#Max(15)
private String password;
private String mobile;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserDAOImpl.java
package com.yogesh.shoponlineback.daoimpl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yogesh.shoponlineback.dao.UserDAO;
import com.yogesh.shoponlineback.model.User;
#Service
#Repository()
public class UserDAOImpl implements UserDAO {
#Autowired
UserDAO userDAO;
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public UserDAOImpl() {
// TODO Auto-generated constructor stub
}
#Transactional
public List<User> list() {
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
#Transactional
public User get(String username) {
return (User) sessionFactory.getCurrentSession().get(User.class, username);
}
#Transactional
public User validate(String username, String password) {
String hql = "from User WHERE username ='" + username + "' and password='" + password + "'";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return (User)query.uniqueResult();
}
#Transactional
public boolean save(User user) {
try {
sessionFactory.getCurrentSession().save(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Transactional
public boolean update(User user) {
try {
sessionFactory.getCurrentSession().update(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
:::::::::::::::::::::::::::::Exception trace::::::::::::::::::::::::::::::::::
INFO: FrameworkServlet 'dispatcher': initialization started
Jan 10, 2017 3:19:22 PM **org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Jan 10 15:19:22 IST 2017]; root of context hierarchy
Jan 10, 2017 3:19:22 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Registering annotated classes: [class com.yogesh.shoponlinefrontend.config.AppConfig]
Jan 10, 2017 3:19:23 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Jan 10, 2017 3:19:23 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Jan 10, 2017 3:19:23 PM org.springframework.web.servlet.DispatcherServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yogesh.shoponlineback.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:592)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at `enter code here`org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at** org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
I have updated to this:
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend,com.yogesh.shoponlineback")
from
#ComponentScan(basePackages = "com.yogesh.shoponlinefrontend)
and it's now working fine.
I had the same problem! My POM file was configured incorrectly.
Check your dependencies (versions).
THis configuration works for me.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stoliarenko</groupId>
<artifactId>CustomerTracker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- <version>1.0-SNAPSHOT</version>-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring.version>5.1.0.RELEASE</spring.version>
<hibernate.version>5.3.5.Final</hibernate.version>
<hibernate.validator>5.4.1.Final</hibernate.validator>
<c3p0.version>0.9.5.2</c3p0.version>
<jstl.version>1.2.1</jstl.version>
<tld.version>1.1.2</tld.version>
<servlets.version>3.1.0</servlets.version>
<jsp.version>2.3.1</jsp.version>
<hsqldb.version>1.8.0.10</hsqldb.version>
</properties>
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator}</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${tld.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlets.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>