Parameter 0 of constructor in com.demo.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found - spring

I am trying to run a simple api flow in java spring and I am getting the following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.nmp.bts.webapps.bsc.btbsc.service.NmpAppService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.>
<Oct 25, 2019 10:37:51 AM EEST> <Notice> <Stdout> <BEA-000000> <WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.>
<Oct 25, 2019 10:37:51 AM EEST> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "48455312047066616" for task "216" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available"
weblogic.application.ModuleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
Truncated. see log file for complete stacktrace
Caused By: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
Truncated. see log file for complete stacktrace
I want to mention that I`ve tried all kind of stuffs starting from the other similar topics on stackoverflow, to change dependency and nothing worked for me.
Controller class: NmpAppController.java
#RestController
#RequestMapping("/api")
public class NmpAppController {
private final NmpAppService nmpAppService;
#Autowired
public NmpAppController(NmpAppService nmpAppService) {
this.nmpAppService = nmpAppService;
}
#GetMapping("/nmp-apps")
public List<NmpApp> getAllNmps() {
try {
return nmpAppService.getAllNmpApps();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Service class: NmpAppService.java
#Service
public class NmpAppService {
private final NmpAppRepository nmpAppRepository;
public NmpAppService(NmpAppRepository nmpAppRepository) {
this.nmpAppRepository = nmpAppRepository;
}
public NmpApp save(final NmpApp nmpApp) {
final NmpApp nmpAppToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public NmpApp update(final NmpApp nmpApp) {
final NmpApp nmpAppitToBeSaved = nmpApp;
NmpApp result = nmpAppRepository.saveAndFlush(nmpAppToBeSaved);
return result;
}
public List<NmpApp> getAllNmpApps() {
return nmpAppRepository.findAll();
}
Repository class: NmpAppRepository.java
#Repository
public interface NmpAppRepository extends JpaRepository<NmpApp, Long> {
}
Domain class NmpApp.java
#Entity
#Table(name = "NMP_APP")
public class NmpApp {
#Id
#Column(name = "SEQ_NO")
private Long seqNo;
#Column(name = "HIST_DATE")
private Long histDate;
public NmpApp() {
}
public NmpApp(Long seqNo, Long histDate) {
this.seqNo = seqNo;
this.histDate = histDate;
}
public Long getSeqNo() {
return seqNo;
}
public void setSeqNo(Long seqNo) {
this.seqNo = seqNo;
}
public Long getHistDate() {
return histDate;
}
public void setHistDate(Long histDate) {
this.histDate = histDate;
}
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>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nmp.bts.webapps.bsc</groupId>
<artifactId>nm-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bt-bsc</name>
<description>BSC</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-jdbc</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Spring boot main class: Application.java
#EnableTransactionManagement
#SpringBootApplication(exclude = {HibernateJpaAutoConfiguration.class})
public class Application extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setHttpOnly(false);
super.onStartup(servletContext);
}
}
Later Edit: I uploaded the application.properties file
#Basic Spring Boot Config for Oracle
spring.datasource.url= jdbc:oracle:thin:#//:/
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.jndi-name=jdbc/DEV_ADF_APPLDS
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.main.allow-bean-definition-overriding=true
I want to be able to perform simple CRUD operations on a database via swagger api caller (code shows only getAll but I do have the rest of code tho).

Usually happens when Spring is missing the spring-boot-starter-data-jpa since Spring infers the EntityManager from the Spring Data JPA which has an out of the box implementation for Hibernate ORM.
Adding the following to project pom.xml usually solves this problem
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
But in your case is available so the offending code is
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Change to
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

Instead of spring-boot-starter-data-rest, try using the following
"org.springframework.boot:spring-boot-starter-data-jpa"
"org.springframework.boot:spring-boot-starter-jdbc"
Later edit: Also, don't forget to add #EnableTransactionManagement on the spring boot main class or on the database configuration class

Related

Why is my security filter chain not working?

I want to permit access to all of my pages and put authentication each page at a time, but I can't even permit access to all my pages. My SecurityConfig is as below (I got this peace of code at spring.io):
#Configuration
public class SecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authz) -> authz
.requestMatchers("/*").permitAll()
);
return http.build();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Once I try to access any endpoint, I get a login screen:
I can't get it to work. Why is it asking authentication to all endpoints of my application? Shouldn't this be enough to permit access to everything?
package com.servicestcg.servicestcg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.servicestcg.servicestcg.controller.CartasController;
#SpringBootApplication
#ComponentScan(basePackageClasses = CartasController.class)
public class ServicesTcgApplication {
public static void main(String[] args) {
SpringApplication.run(ServicesTcgApplication.class, args);
}
}
<?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.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.services-tcg</groupId>
<artifactId>services-tcg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>services-tcg</name>
<description>Services for tcg website</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</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>
<configuration>
<executable>true</executable>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
With Spring Security, the sigle "all" is exprimed with "**".
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorization -> authorization
.requestMatchers("/**").permitAll()
);
return http.build();
}
You may encounter another problem with
#SpringBootApplication
#ComponentScan(basePackageClasses = CartasController.class)
public class ServicesTcgApplication {
public static void main(String[] args) {
SpringApplication.run(ServicesTcgApplication.class, args);
}
}
Unless you know what you're doing, you should let spring handle the package scanning for you.
#SpringBootApplication
public class ServicesTcgApplication {
public static void main(String[] args) {
SpringApplication.run(ServicesTcgApplication.class, args);
}
}
More information on Spring Security on https://docs.spring.io/spring-security/reference/index.html

Error creating bean with name 'dietaController'

So, I have a problem like this:
2020-01-30 22:54:20.059 ERROR 8040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dietaController': Unsatisfied dependency expressed through field 'dietaRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dietaRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.diet4you.LapkoEkaterina.Entity.Dieta
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>org.diet4you</groupId>
<artifactId>LapkoEkaterina</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Entity:
#Entity
#Table(name = "diety")
public class Dieta {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="DIETA_ID") private int dietaId;
#NotEmpty
#Column(unique=true, name ="DIETA_NAZWA")
private String nazwa;
#NotEmpty
#Column(name="OPIS") private String opis;
public Dieta(){ }
public Dieta (int dietaId,String nazwa, String opis )
{ this.dietaId = dietaId;
this.nazwa = nazwa;
this.opis = opis; }
public int getDietaId() {
return dietaId; }
public void setDietaId(int dietaId) {
this.dietaId = dietaId; }
public String getNazwa() {
return nazwa; }
public void setNazwa(String nazwa) {
this.nazwa = nazwa; }
public String getOpis() {
return opis; }
public void setOpis(String opis) {
this.opis = opis; }
}
My repository:
#Repository
public interface DietaRepository extends JpaRepository<Dieta, String> {
Dieta findByName (String name);
}
And my Controller:
#RestController
public class DietaController {
#Autowired
private DietaRepository dietaRepository;
#GetMapping("/dieta")
public List<Dieta> getAllNotes() {
return dietaRepository.findAll();
}
}
Application java class:
#Configuration
#SpringBootApplication
#EnableJpaRepositories
#EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
remove space here #EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" }) between " and com.diet4you...
change extends JpaRepository<Dieta, String> to extends JpaRepository<Dieta, Integer>
remove or fix Dieta findByName (String name) at repository interface, it's mistake

When Spring boot project war deployed in tomcat 8 server not working for serving images

Web config for static resources
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("file:///C:/test/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Project 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.test</groupId>
<artifactId>test</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>project</name>
<description>test.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<jersey.version>2.7</jersey.version>
<guava.version>18.0</guava.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Dependencies for GuavaCacheManager -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- Dependencies for Unit Testing -->
<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-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application configuration
#Configuration
#SpringBootApplication
#EnableTransactionManagement
#EnableCaching
#EnableAsync
#EnableAutoConfiguration
#EnableScheduling
#ComponentScan
public class Application {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Entry point for the application.
*
* #param args
* Command line arguments.
* #throws Exception
* Thrown when an unexpected Exception is thrown from the
* application.
*/
public static void main(final String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
/**
* Create a CacheManager implementation class to be used by Spring where
*
<code>#Cacheable</code> annotations are applied.
*
* #return A CacheManager instance.
*/
#Bean
public CacheManager cacheManager() {
final GuavaCacheManager cacheManager = new GuavaCacheManager("greetings");
return cacheManager;
}
/**
* Supplies a PasswordEncoder instance to the Spring ApplicationContext. The
* PasswordEncoder is used by the AuthenticationProvider to perform one-way
* hash operations on passwords for credential comparison.
*
* #return A PasswordEncoder.
*/
#Bean
public PasswordEncoder passwordEncoder() {
this.logger.info("passwordEncoder");
return new BCryptPasswordEncoder();
}
public #Bean MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient("127.0.0.1"), "test");
return mongoTemplate;
}
}
In eclipse if I start spring boot application, then application serving images for this url
http://localhost:8080///////images//profile//APM1184//originalImage_7a7zke527_.jpeg
If I deploy war file of this project in local tomcat 8 and start. This URL is not working saying 404 not found.
I have posted my code. please correct me where I went wrong.
Having hard coded resource locations and mongo hosts is going to make it hard for you to manage your application. I would recommend moving those values into a configuration file. At the same time I would recommend using relative or root directory locations for resources instead of having the C:\ in the path as that won't work for deployments to Linux or other environments where the resource isn't on the C:\. My guess is that Tomcat isn't allowing the application to read from that external location due to some security constraints on the Tomcat installation.
I would recommend reading this Getting Started Guide on serving static content: https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

spring boot build a war file deploy into an external container, error:NoSuchBeanDefinitionException: No qualifying bean of type

Trying to build a war file that is both executable and deployable into an external container and I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jusfoun.test.service.TestService com.jusfoun.test.controller.TestController.testService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.jusfoun.test.dao.TestMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
It works when started up via java -jar test.war
Project:
pom.xml:
<project>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--Quartz setting -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!--junit setting -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- datasource heroku -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java6</artifactId>
<exclusions>
<exclusion>
<artifactId>tools</artifactId>
<groupId>com.sun</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- aspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- Spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Provided (for embedded war support) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- myBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.6.3</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- javax -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
<version>2.4</version>
</dependency>
<!-- other service dependency package of jusfoun -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>true</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
</project>
Application.java:
#Configuration
#ComponentScan({"com.jusfoun.test"})
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<Application> applicationClass = Application.class;
}
TestController.java
package com.jusfoun.test.controller;
#RestController
#RequestMapping(value = "/test")
public class TestController {
#Autowired
private TestService testService;
/**
* GET /test -> show test
*/
#RequestMapping(value = "/get", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String test() {
System.out.println("teststestestsetstsetest");
return testService.test();
}
}
TestService.java
package com.jusfoun.test.service;
public interface TestService {
String test();
}
TestServiceImpl.java
package com.jusfoun.test.service.impl;
#Service
public class TestServiceImpl implements TestService {
#Resource
private TestMapper testMapper;
#Override
public String test() {
List<Test> tlist = testMapper.selectByExample(null);
JSONArray array = JSONArray.fromObject(tlist);
return array.toString();
}
}
TestMapper.java
package com.jusfoun.test.dao;
#Component
public interface TestMapper {
...
}
TestMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jusfoun.test.dao.TestMapper" >
...
MapperClassNamePlugin
package com.jusfoun.test.dao.mybatis.plugin;
import java.util.List;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MapperClassNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
#Override
public void initialized(IntrospectedTable table) {
super.initialized(table);
table.setMyBatis3JavaMapperType(table.getMyBatis3JavaMapperType()
.replaceAll("Mapper$", "Dao"));
}
}
MapperXmlNamePlugin
package com.jusfoun.test.dao.mybatis.plugin;
import java.util.List;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
public class MapperXmlNamePlugin extends PluginAdapter {
public boolean validate(List<String> warnings) {
return true;
}
#Override
public void initialized(IntrospectedTable table) {
super.initialized(table);
table.setMyBatis3JavaMapperType(table.getMyBatis3JavaMapperType()
.replaceAll("Mapper", ""));
}
}
DataBaseConfiguration.java
#Configuration
#EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private static Logger log = LoggerFactory
.getLogger(DataBaseConfiguration.class);
private Environment env;
#Override
public void setEnvironment(Environment env) {
this.env = env;
this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
}
#Bean(destroyMethod = "shutdown")
public DataSource dataSource() {
log.debug("Configruing DataSource");
if (propertyResolver.getProperty("url") == null
&& propertyResolver.getProperty("databaseName") == null) {
log.error("Your database conncetion pool configuration is incorrct ! The application "
+ "cannot start . Please check your jdbc");
Arrays.toString(env.getActiveProfiles());
throw new ApplicationContextException(
"DataBase connection pool is not configured correctly");
}
HikariConfig config = new HikariConfig();
config.setDataSourceClassName(propertyResolver
.getProperty("dataSourceClassName"));
if (propertyResolver.getProperty("url") == null
|| "".equals(propertyResolver.getProperty("url"))) {
config.addDataSourceProperty("databaseName",
propertyResolver.getProperty("databaseName"));
config.addDataSourceProperty("serverName",
propertyResolver.getProperty("serverName"));
} else {
config.addDataSourceProperty("url",
propertyResolver.getProperty("url"));
}
config.setUsername(propertyResolver.getProperty("username"));
config.setPassword(propertyResolver.getProperty("password"));
if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
.equals(propertyResolver.getProperty("dataSourceName"))) {
config.addDataSourceProperty("cachePrepStmts",
propertyResolver.getProperty("cachePrepStmts"));
config.addDataSourceProperty("prepStmtCacheSize",
propertyResolver.getProperty("prepStmtsCacheSize"));
config.addDataSourceProperty("prepStmtCacheSqlLimit",
propertyResolver.getProperty("prepStmtCacheSqlLimit"));
config.addDataSourceProperty("userServerPrepStmts",
propertyResolver.getProperty("userServerPrepStmts"));
}
return new HikariDataSource(config);
}
}
MybatisConfiguration.java
#Configuration
#ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
#AutoConfigureAfter({ DataBaseConfiguration.class })
#MapperScan(basePackages={"com.jusfoun.test.dao"})
public class MybatisConfiguration implements EnvironmentAware {
private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
#Inject
private DataSource dataSource;
#Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
}
#Bean
#ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory() {
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(propertyResolver
.getProperty("typeAliasesPackage"));
sessionFactory
.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(propertyResolver
.getProperty("mapperLocations")));
sessionFactory
.setConfigLocation(new DefaultResourceLoader()
.getResource(propertyResolver
.getProperty("configLocation")));
return sessionFactory.getObject();
} catch (Exception e) {
logger.warn("Could not confiure mybatis session factory");
return null;
}
}
#Bean
#ConditionalOnMissingBean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
Using mybatis-spring-boot-starter (https://github.com/mybatis/spring-boot-starter), your setup can be simplified to the following:
Remove DataBaseConfiguration and MybatisConfiguration (which will be done by mybatis-spring-boot-starter.
Modifiy TestMapper:
package com.jusfoun.test.dao;
#Mapper
public interface TestMapper {
...
}
I remove annotation of #ConditionalOnClass in MybatisConfiguration.
The project works when war deploy into an external container(tomcat8).
Before remove the annotation, it works with java -jar xxx.war but not works deploy into external tomcat.
#Configuration
#AutoConfigureAfter({ DataBaseConfiguration.class })
#MapperScan(basePackages={"com.jusfoun.test.dao"})
public class MybatisConfiguration implements EnvironmentAware {

Where I should place the jsp files in a spring-boot project

Recently, I start to work with the spring-boot, and I am trying convert my old spring projects, all of them being web applications, to use this. I manage to compile, package and run the application, but when I try access them in the browser, I can't reach out my views.
First, I try put the jsp pages in the usual folder src/main/webapp/WEB-INF/jsp, but after read this article from official documentation:
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content
I try put them in the folder src/main/resources. None of this works. Anyone can tell me where I should put this files to allow them be acessible when the application is running?
My pom.xml is this:
<?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.spring</groupId>
<artifactId>app</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<start-class>com.spring.app.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have this controller to map the views:
#Controller
public class AcessoController {
#RequestMapping(value = "/signin")
public String signin(Model model) {
return "acesso/signin";
}
#RequestMapping(value = "/admin")
public String admin(Model model) {
return "private/admin";
}
#RequestMapping(value = "/index")
public String index(Model model) {
return "public/index";
}
}
and this configuration classes:
WebAppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan(value="com.spring.app")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebAppInitializer.java
#Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
#SuppressWarnings("resource")
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.class);
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext jspContext = new AnnotationConfigWebApplicationContext();
jspContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(jspContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
DispatcherConfig.java
#Configuration
#Import(WebAppConfig.class)
public class DispatcherConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
If using Jetty or Tomcat as embedded servlet container just change your packaging from jar to war, and launch it with java -jar ...

Resources