Я создаю простой REST API с пружиной mvc, но когда я go до http://localhost: 8080 / fundnesia / api / loan я получил noHandlerFound eror. Похоже, Spring не регистрирует эти аннотации @RestController, @RequestMapping и @PostMapping, @DeleteMapping. Любая помощь, пожалуйста
Вот мой класс сущности
package com.fundnesia.entity;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="loan")
public class Loan {
@Id
@GeneratedValue(strategy =GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="tenure")
private int tenure;
@Column(name="ticket_size")
private BigDecimal ticketSize;
@Column(name="fee")
private BigDecimal fee;
@Column(name="total_loan")
private BigDecimal totalLoan;
@Column(name="installment_per_month")
private BigDecimal installmentPerMonth;
@Column(name="status")
private String status;
public Loan() {
}
public Loan(int tenure, BigDecimal ticketSize, BigDecimal fee, BigDecimal totalLoan, BigDecimal installmentPerMonth,
String status) {
this.tenure = tenure;
this.ticketSize = ticketSize;
this.fee = fee;
this.totalLoan = totalLoan;
this.installmentPerMonth = installmentPerMonth;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTenure() {
return tenure;
}
public void setTenure(int tenure) {
this.tenure = tenure;
}
public BigDecimal getTicketSize() {
return ticketSize;
}
public void setTicketSize(BigDecimal ticketSize) {
this.ticketSize = ticketSize;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public BigDecimal getTotalLoan() {
return totalLoan;
}
public void setTotalLoan(BigDecimal totalLoan) {
this.totalLoan = totalLoan;
}
public BigDecimal getInstallmentPerMonth() {
return installmentPerMonth;
}
public void setInstallmentPerMonth(BigDecimal installmentPerMonth) {
this.installmentPerMonth = installmentPerMonth;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Loan [id=" + id + ", ticketSize=" + ticketSize + ", fee=" + fee + ", totalLoan=" + totalLoan
+ ", installmentPerMonth=" + installmentPerMonth + ", status=" + status + "]";
}
}
Вот файл конфигурации
package com.fundnesia.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import
org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
import
org.springframework.web.servlet.config.annotation.EnableWebMvc;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages="com.fundnesia")
@PropertySource({"classpath:persistence-mysql.properties"})
public class RestConfig implements WebMvcConfigurer {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
ComboPooledDataSource dataSource =new ComboPooledDataSource();
try {
dataSource.setDriverClass(env.getProperty("jdbc.driver"));
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.password"));
dataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
dataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory =new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
private Properties hibernateProperties() {
Properties properties =new Properties();
properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager txManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager =new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
Здесь инициализатор DispetcherServlet
package com.fundnesia.config;
importorg.springframework.web.servlet.support.
AbstractAnnotationConfigDispatcherServletInitializer;
public class ConfigInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {RestConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
Класс контроллера
package com.fundnesia.controller;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fundnesia.entity.Loan;
import com.fundnesia.service.LoanService;
@RestController
@RequestMapping("/fundnesia/api")
public class LoanResource {
@Autowired
private LoanService loanService;
@GetMapping("/loans")
public List<Loan> findAll() {
List<Loan> loans= loanService.findAll();
return loans;
}
@GetMapping("/loans/{loanId}")
public Loan findById(@PathVariable("loanId") int loanId) {
return loanService.findById(loanId);
}
@PostMapping("/loans")
public Loan save(@RequestBody Loan loan) {
BigDecimal ticketSize =loan.getTicketSize();
int tenure =loan.getTenure();
BigDecimal fee =ticketSize.multiply(BigDecimal.valueOf(tenure * 0.02));
BigDecimal totalLoan =ticketSize.add(fee);
BigDecimal installmentPerMonth =totalLoan.divide(BigDecimal.valueOf(tenure));
loan.setFee(fee);
loan.setTotalLoan(totalLoan);
loan.setInstallmentPerMonth(installmentPerMonth);
loan.setStatus("SUBMITTED");
loanService.save(loan);
return loan;
}
@DeleteMapping("/loans/{loanId}")
public String deleteById(@PathVariable("loanId") int loanId) {
loanService.deleteById(loanId);
return "Deleted loan with Id: " + loanId;
}
}
Класс обслуживания Impl
package com.fundnesia.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fundnesia.dao.LoanDao;
import com.fundnesia.entity.Loan;
@Service
public class LoanServiceImpl implements LoanService {
@Autowired
private LoanDao loanDao;
@Override
@Transactional
public List<Loan> findAll() {
return loanDao.findAll();
}
@Override
@Transactional
public void save(Loan loan) {
loanDao.save(loan);
}
@Override
@Transactional
public Loan findById(int loanId) {
return loanDao.findById(loanId);
}
@Override
@Transactional
public void deleteById(int loanId) {
loanDao.deleteById(loanId);
}
}
Класс Dao Impl
package com.fundnesia.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fundnesia.entity.Loan;
@Repository
public class LoanDaoImpl implements LoanDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<Loan> findAll() {
Session session =sessionFactory.getCurrentSession();
Query<Loan> query =session.createQuery("from Loan", Loan.class);
return query.getResultList();
}
@Override
public void save(Loan loan) {
Session session =sessionFactory.getCurrentSession();
session.saveOrUpdate(loan);
}
@Override
public Loan findById(int loanId) {
Session session =sessionFactory.getCurrentSession();
return session.get(Loan.class, loanId);
}
@Override
public void deleteById(int loanId) {
Session session =sessionFactory.getCurrentSession();
Query query =session.createQuery("delete from Loan where id=:loanId");
query.setParameter("loanId", loanId);
query.executeUpdate();
}
}
POM-файл
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sagala</groupId>
<artifactId>fundnesia</artifactId>
<packaging>war</packaging>
<version>0.01</version>
<name>fundnesia Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.2.5.RELEASE</springframework.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.3</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<finalName>fundnesia</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
StackTrace
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name: Apache Tomcat/9.0.30
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Dec 7 2019 16:42:04 UTC
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.30.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: x86
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_162
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_162-b12
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Program Files\Apache Software
Foundation\Tomcat 9.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -
Dcatalina.base=C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program
Files\Apache Software Foundation\Tomcat 9.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
\wtpwebapps
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program
Files\Apache Software Foundation\Tomcat 9.0\endorsed
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Mei 02, 2020 12:02:03 PM
org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows
optimal performance in production environments was not found on the
java.library.path: [C:\Program
Files\Java\jre1.8.0_162\bin;C:\Windows\Sun\Java\bin;C:\Windows\
system32;C:\Windows;C:/Program
Files/Java/jre1.8.0_162/bin/client;C:/Program
Files/Java/jre1.8.0_162/bin;C:/Program
Files/Java/jre1.8.0_162/lib/i386;C:\ProgramData\Oracle\Java\
javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files\Git\cmd;C:\Program Files\Git\mingw32\bin;C:\Program
Files\Git\usr\bin;;C:\Users\Tunggul\AppData\Local\Programs\
Microsoft VS Code\bin;C:\Program Files\eclipse;;.]
Mei 02, 2020 12:02:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Mei 02, 2020 12:02:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Mei 02, 2020 12:02:03 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [980] milliseconds
Mei 02, 2020 12:02:04 PM org.apache.catalina.core.StandardService
startInternal
INFO: Starting service [Catalina]
Mei 02, 2020 12:02:04 PM org.apache.catalina.core.StandardEngine
startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.30]
Mei 02, 2020 12:02:08 PM org.apache.jasper.servlet.TldScanner
scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs.
Enable debug logging for this logger for a complete list of JARs
that were scanned but no TLDs were found in them. Skipping unneeded
JARs during scanning can improve startup time and JSP compilation
time.
Mei 02, 2020 12:02:15 PM
org.apache.catalina.core.ApplicationContext log
INFO: 1 Spring WebApplicationInitializers detected on classpath
Mei 02, 2020 12:02:15 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs.
Enable debug logging for this logger for a complete list of JARs
that were scanned but no TLDs were found in them. Skipping unneeded
JARs during scanning can improve startup time and JSP compilation
time.
Mei 02, 2020 12:02:15 PM
org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring DispatcherServlet 'dispatcher'
Mei 02, 2020 12:02:15 PM
org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Initializing Servlet 'dispatcher'
Mei 02, 2020 12:02:16 PM com.mchange.v2.log.MLog
INFO: MLog clients using java 1.4+ standard logging.
Mei 02, 2020 12:02:16 PM com.mchange.v2.c3p0.C3P0Registry
INFO: Initializing c3p0-0.9.5.3 [built 27-January-2019 00:11:37
-0800; debug? true; trace: 10]
Mei 02, 2020 12:02:17 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.1.Final}
Mei 02, 2020 12:02:17 PM
org.hibernate.annotations.common.reflection.java.
JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Mei 02, 2020 12:02:18 PM
com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
INFO: Initializing c3p0 pool...
com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3,
acquireRetryAttempts -> 30, acquireRetryDelay -> 1000,
autoCommitOnClose -> false, automaticTestTable -> null,
breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName ->
com.mchange.v2.c3p0.impl.DefaultConnectionTester,
contextClassLoaderSource -> caller, dataSourceName ->
1hge9kua91mr8xjwcsbkvv|8b45e, debugUnreturnedConnectionStackTraces
-> false, description -> null, driverClass ->
com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation ->
null, forceIgnoreUnresolvedTransactions -> false,
forceSynchronousCheckins -> false, forceUseNamedDriverClass ->
false, identityToken -> 1hge9kua91mr8xjwcsbkvv|8b45e,
idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl ->
jdbc:mysql://localhost:3306/loan_calculator?useSSL=false,
maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime
-> 3000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20,
maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize ->
5, numHelperThreads -> 3, preferredTestQuery -> null,
privilegeSpawnedThreads -> false, properties -> {user=******,
password=******}, propertyCycle -> 0,
statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin
-> false, testConnectionOnCheckout -> false,
unreturnedConnectionTimeout -> 0, userOverrides -> {},
usesTraditionalReflectiveProxies -> false ]
Mei 02, 2020 12:02:18 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mei 02, 2020 12:02:20 PM
org.hibernate.engine.transaction.jta.platform.internal.
JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
Mei 02, 2020 12:02:21 PM
org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Completed initialization in 6287 ms
Mei 02, 2020 12:02:21 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Mei 02, 2020 12:02:21 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Mei 02, 2020 12:02:21 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [17,684] milliseconds
Mei 02, 2020 12:02:23 PM
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /fundnesia/api/loans