Not finding repository class in spring integration test - spring-data-jpa

The methods : findAll(),save(O o), findOne(long id) of interface
Repository is not found in my spring jpa integration test.
package source;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import category.IntegrationTest;
import domain.BankAccount;
import presentation.MessageContext;
import repository.BankAccountRepository;
#RunWith(SpringRunner.class)
#Category(IntegrationTest.class)
#DataJpaTest
public class BankAccountTest {
#Autowired
private BankAccountRepository repository;
#Test
public void should_find_no_customers_if_repository_is_empty() {
Iterable<BankAccount> accounts = repository.findAll();
assertNull(accounts);
}
#Test
public void shuldCreateBankAccount() {
BankAccount accounts = new BankAccount(100);
repository.save(accounts);
BankAccount accountr = repository.findOne(1l);
assertNotNull(accountr);
}
}
The repository interface looks like this
package repository;
import org.springframework.data.repository.Repository;
import domain.BankAccount;
public interface BankAccountRepository extends Repository<BankAccount, Long> {}
I have also implemeneted a configuration file
package repository;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#EnableJpaRepositories
public class PersistentContext {}
the classes is placed like this
Component structure
What must i to compile the code without errors?

interface Repository is empty interface ,it's common interface for spring data repositories . There is no any method , see Repository API .
If you need method findAll(),save(O o), findOne(long id) you need use CrudRepository - it's sub interface for interface Repository , or you can use JpaRepository - it's extension of CrudRepository.

Related

How to use Rest Service while using Spring Boot & Spring Data Jpa

Im working on a spring boot application for rest service with using spring data jpa. I followed instructors and read much answers but I couldn't fix my rest service.
Here is application.class
package tr.kasim.Application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("tr.kasim.Dao")
#EntityScan("tr.kasim.Model")
#ComponentScan({"tr.kasim.Service", "tr.kasim.Application" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Here is `restcontroller.class
package tr.kasim.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tr.kasim.Service.PersonelService;
import tr.kasim.Model.Personel;
#RestController
public class STRestController {
#Autowired
public PersonelService personelService;
#RequestMapping(value = "/api/personels", method = RequestMethod.GET)
public ResponseEntity<List<Personel>> getPersonels(){
List<Personel> personels = personelService.findAll();
return ResponseEntity.ok().body(personels);
}
}
`
Here is Service.class`
package tr.kasim.Service;
import java.util.List;
import tr.kasim.Model.Personel;
public interface PersonelService {
List<Personel> findAll();
}
`
Here is ServiceImplemantion.class
package tr.kasim.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tr.kasim.Dao.PersonelDao;
import tr.kasim.Model.Personel;
#Service
public class PersonelServiceImpl implements PersonelService {
#Autowired
private PersonelDao personelDao;
#Override
#Transactional
public List<Personel> findAll() {
return personelDao.findAll();
}
}
Here is Dao.class
package tr.kasim.Dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import tr.kasim.Model.Personel;
#Repository
public interface PersonelDao extends JpaRepository<Personel, Long> {
List<Personel> findAll();
}
Lastly here is my application.properties
#MySql Connection
spring.datasource.url=jdbc:mysql://localhost:3306/exampleproject?verifyServerCertificate=false&useSSL=true
spring.datasource.username=root
spring.datasource.password=*******
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Jpa/Hibernate
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#Logging
logging.file=staffTracking.log
logging.level.org.springframework.web=debug
Im not sure about componentScan. When I read answers I discovered someone mentioned about it but I tried and I got still nothing. Please show me where I failed. Best Regards.
I updated Application.class, now I can deploying project but rest service not working still.
How did you try ComponentScan? The issue here seems that you have a package structure like this:
tr.kasim.Application
- Application.java
tr.kasim.Service
- PersonelService.java
- PersonelServiceImpl.java
tr.kasim.Dao
- PersonelDao.java
Now since, the mainClass is in tr.kasim.Application it would scan for bean definitions inside that package (or a sub-package in tr.kasim.Application). So,
either you move the mainClass out to a parent-package like tr.kasim, or
use #ComponentScan({ "tr.kasim.Dao", "tr.kasim.Service", "tr.kasim.Application" }) and so on.
-- Update --
Based on the discussion so far, I'd suggest taking the first option as that reduces the effort to manually enable scan for entity, repository, etc.

What is the framework class in Spring that distinguishes functionality of #Controller, #Service, #Repository

I want to understand which class in Spring framework distinguishes functionality of #Controller, #Service, #Repository annotations. Upon comparing source code of these three annotations understood that only class name is different.
Say, how does spring understand StudentController is only Controller and not Service or Repository?
#Controller
public class StudentController {
}
#Service
public class StudentService {
}
#Repository
public class StudentRepository {
}
Source codes of spring stereotype annotations
Controller.class
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Component
public #interface Controller {
#AliasFor(
annotation = Component.class
)
String value() default "";
}
Service.class
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Component
public #interface Service {
#AliasFor(
annotation = Component.class
)
String value() default "";
}
Repository.class
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Component
public #interface Repository {
#AliasFor(
annotation = Component.class
)
String value() default "";
}
Since source code is same for these annotations, their functionality is distinguished (as each one has different use cases) in framework classes somewhere otherwise framework allows users to use these annotations interchangeable.
I want to understand which class in Spring framework distinguishes
functionality of #Controller, #Service, #Repository annotations. Upon
comparing source code of these three annotations understood that only
class name is different.
The usage is nuanced and often your answers are going to be found by searching for references (e.g. in Eclipse.
For example, #Controller is referenced specifically in RequestMappingHandlerMapping.
Say, how does spring understand StudentController is only Controller
and not Service or Repository?
The plumbing knows what to do with specific annotations. To answer your question directly: it knows StudentController is an #Controller because you have annotated it thus. It is not annotated as #Repository, so it's not a repository.
#Controller itself has a RetentionType.RUNTIME so that Spring can inspect / check for it using reflection.
Finally, note that #Controller (and the other stereotypes you mentioned) are themselves #Components. So a type marked as #Controller is implicitly also a #Component.

HikariCP for MongoDB in springboot

I am looking to create a connection pool - for mongoDB in Springboot. I am currently making use of Springdata Mongo repositories to connect to DB and collections but unsure of how to create the datapool connection
Here is the current implementation
PersonRepository.java
package com.test.TestAPI.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.test.TestAPI.dto.Person;
#Repository
public interface PersonRepository extends MongoRepository<Person, String> {
}
PersonService
package com.test.TestAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Service
public class PersonService {
#Autowired
private PersonRepository personRepo;
public List<Person> findAllPersons() {
return personRepo.findAll();
}
public Person createPerson(Person person) {
return personRepo.save(person);
}
}
PersonController
package com.test.TestAPI.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.TestAPI.service.impl.PersonService;
import com.test.TestAPI.dto.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#RestController
#RequestMapping(path="/v1/personController")
#Api(value="Controller for Person document")
public class PersonController {
#Autowired
PersonService service;
#GetMapping("/getAllPersons")
#ApiOperation(produces = MediaType.APPLICATION_JSON_VALUE, httpMethod = "GET", response = List.class,
value = "getAllPersons from the database", notes = "Sample note")
public ResponseEntity<List<Person>> getAllPersons(){
List<Person> personList = service.findAllPersons();
return new ResponseEntity<List<Person>>(personList, HttpStatus.OK);
}
}
SimpleCommandLineConfig
package com.test.TestAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Component;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Component
#Order(3)
public class SimpleCommandLineConfig implements CommandLineRunner {
#Autowired
PersonRepository repo;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("third command line runner");
System.out.println(repo.save(new Person("rr","rr",4)));
}
}
App.java
package com.test.TestAPI.main;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* Hello world!
*
*/
#SpringBootApplication
#ComponentScan(basePackages= {"com.test.TestAPI"})
#EnableMongoRepositories(basePackages= {"com.test.TestAPI.repository"})
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
Also, I would like to know if spring data repos like a custom repo for MongoDB takes care of connection pool mechanism? How does connection pooling happen in that case? Could you please help me on this
I think I found an answer for this. Just like we use JDBC templates for RDBMS to store the databases, spring provides something called MongoTemplates which forms a connection pool based on the db configuration given
Here is a sample implementation
MongoClientFactory.java
public #Bean MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
.connectionsPerHost(2000)
.connectTimeout(4000)
//.maxConnectionIdleTime(1000000000)
.maxWaitTime(3000)
.retryWrites(true)
.socketTimeout(4000)
.sslInvalidHostNameAllowed(true)//this is very risky
.build();
mongo.setMongoClientOptions(clientOptions);
return mongo;
}
DataSourceConfig.java (Another config class. Same config class can also be used to define all beans)
package com.fmr.FeedBackAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
#Configuration
#Import(value=MongoClientFactory.class)
public class DataSourceConfig {
#Autowired
Mongo mongo;
#Autowired
Environment env;
#Bean
public String test() {
System.out.println("mongo"+mongo);
return "rer";
}
private MongoTemplate mongoTemplate() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
MongoTemplate template = new MongoTemplate(factory);
return template;
}
#Bean
#Qualifier(value="customMongoOps")
public MongoOperations mongoOps() {
MongoOperations ops = mongoTemplate();
return ops;
}
#Bean
public MongoDbFactory factory() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
return factory;
}
// #Bean
// public GridFsTemplate gridFsTemplate() {
// return new GridFsTemplate(mongo, converter)
// }
#Bean
public javax.sql.DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(100);
// ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
// ds.setJdbcUrl(env.getProperty("spring.datasource.url"));;
//ds.setUsername(env.getProperty("spring.datasource.username"));
//ds.setPassword(env.getProperty("spring.datasource.password"));
ds.addDataSourceProperty("cachePrepStmts", true);
ds.addDataSourceProperty("prepStmtCacheSize", 250);
ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
ds.addDataSourceProperty("useServerPrepStmts", true);
return ds;
}
}
Now autowire the template/mongoOperations in you dao implementation or service and use it
package com.fmr.FeedBackAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.fmr.FeedBackAPI.dto.ConfigDTO;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
#Service
public class PlanConfigService {
#Autowired
#Qualifier(value="customMongoOps")
MongoOperations mongoOps;
public List<ConfigDTO> createConfigDTOList(List<ConfigDTO> configDTOList) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.insert(configDTOList, ConfigDTO.class);
configList = mongoOps.findAll(ConfigDTO.class, "ConfigDTO_table");
return configList;
}
public List<ConfigDTO> createConfigDTO(ConfigDTO configDTO) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.save(configDTO);
configList = mongoOps.find(query(where("planId").is(configDTO.getPlanId())), ConfigDTO.class,"ConfigDTO_table");
return configList;
}
}
Here is the application.properties (this is the default instance running in local)
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mongo_test
spring.data.mongodb.repositories=true
#
spring.datasource.url=jdbc:mongodb://localhost:27017/mongo_test

Will Spring Mail module be alternate to javax.mail

I have a Spring boot application where I need to send an alert mail to both a gmail account and a Zoho account. I try to use Javax.mail, where I set the properties of a both Gmail and a Zoho account using Java class and use it. Will Spring mail be a best replacement for Javax.mail. I have a doubt if Spring mail module can be used because we set the SMTP server properties in application.yml
The first thing to do is to import the dependency from Maven Central Repository.
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>spring-boot-email-core</artifactId>
<version>0.5.0</version>
</dependency>
Then, you populate the application.yml with the following entries
spring.mail.host: smtp.gmail.com
spring.mail.port: 587
spring.mail.username: hari.seldon#gmail.com
spring.mail.password: Th3MuleWh0
spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.properties.mail.smtp.starttls.required: true
Now, for the sake of the example, assume that you have a service that sends a very simple plain text email. It will be something like:
package com.test;
import com.google.common.collect.Lists;
import it.ozimov.springboot.mail.model.Email;
import it.ozimov.springboot.mail.model.defaultimpl.DefaultEmail;
import it.ozimov.springboot.mail.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import static com.google.common.collect.Lists.newArrayList;
#Service
public class TestService {
#Autowired
private EmailService emailService;
public void sendEmail() throws UnsupportedEncodingException {
final Email email = DefaultEmail.builder()
.from(new InternetAddress("hari.seldon#the-foundation.gal",
"Hari Seldon"))
.to(newArrayList(
new InternetAddress("the-real-cleon#trantor.gov",
"Cleon I")))
.subject("You shall die! It's not me, it's Psychohistory")
.body("Hello Planet!")
.encoding("UTF-8").build();
emailService.send(email);
}
}
Let's do it in the main application, where we'll send the email just after starting and initialising the Spring context.
package com.test;
import it.ozimov.springboot.mail.configuration.EnableEmailTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.batch.JobExecutionExitCodeGenerator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
#SpringBootApplication
#EnableEmailTools
public class PlainTextApplication {
#Autowired
private TestService testService;
public static void main(String[] args) {
SpringApplication.run(PlainTextApplication.class, args);
}
#PostConstruct
public void sendEmail() throws UnsupportedEncodingException, InterruptedException {
testService.sendEmail();
}
}
Observe that to enable the Email Tools you need to annotate the main app with the annotation
#EnableEmailTools
that will trigger the configuration class for the extension.

Spring-boot, unable to autowire a class.No default constructor found Exception is raised

I am new to spring-boot. After i moved a class to different package (other the one contains 'Application'), Could not instantiate bean class: No default constructor found Exception is raised.
Before (workable code)
package com.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
#Configuration
#ComponentScan(basePackages = {"com.server" })
#EnableAutoConfiguration
#Profile({ "default" })
#Controller
public class Application {
private static Log logger = LogFactory.getLog(Application.class);
public static void main(String[] args) {
logger.info("Starting Application...");
SpringApplication.run(Application.class, args);
}
}
A piece of code from http://bitwiseor.com/2013/09/20/creating-test-services-with-spring-boot/
package com.server;
import java.util.Collections;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#Controller
#Profile({ "default" })
class Franchise {
private JdbcTemplate jdbcTemplate;
#Autowired
public Franchise(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#ResponseBody
#RequestMapping("/api/franchise/{id}")
String franchiseId(#PathVariable Long id) {
try {
return jdbcTemplate.queryForMap("SELECT id, title FROM franchises WHERE id=?", id).toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
#ResponseBody
#RequestMapping("/api/franchise")
String franchises() {
try {
return jdbcTemplate.queryForList("SELECT id, title FROM franchises").toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
}
I am able to bring up the server when class 'Application' and 'Franchise' are located in the same package. However, when I moved the class 'Franchise' into another package as shown below, I've got this exception: Could not instantiate bean class: No default constructor found Exception is raised.
package com.server.api;
import java.util.Collections;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#Controller
#Profile({ "default" })
class Franchise {
private JdbcTemplate jdbcTemplate;
#Autowired
public Franchise(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#ResponseBody
#RequestMapping("/api/franchise/{id}")
String franchiseId(#PathVariable Long id) {
try {
return jdbcTemplate.queryForMap("SELECT id, title FROM franchises WHERE id=?", id).toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
#ResponseBody
#RequestMapping("/api/franchise")
String franchises() {
try {
return jdbcTemplate.queryForList("SELECT id, title FROM franchises").toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
}
How can I solve this problem if I wanted to move this class into a different package?
Thanks!
Edit: I found a solution
When I removed the following tag, I am able to put the class into separate package.
#Configuration
#Profile({ "default" })
But I have no idea why...
It looks to me like your Franchise class is package private (the default visibility for a java class). That would explain everything (and no need to involve Spring or anything other than a compiler). To fix it just declare your class to be "public".
Marten is also correct that #Configuration is probably not want you mean for the Franchise (but in this case it's harmless).