Why I receive error when use Cover As in Eclipse and not with Junit? - eclipse

I use Eclipse with eCobertura
I have a little project with a Controller (SpringMVC).
I created a test (JUnit).
When I run the test from JUnit (in Eclipse IDE) all is right but when I run the command (from menu) I receive an error
My controller :
package ec.europa.eu.nwi.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* #author LEBRUJA
*/
#Controller
public class AvailibilityController {
/**
* #param request
* #return mav
*/
#RequestMapping(value = "/available")
public final ModelAndView available(final HttpServletRequest request) {
final ModelAndView mav = new ModelAndView("available", "sample",
new String("availability on 0.0.1"));
return mav;
}
}
My Test :
package ec.europa.eu.nwi.web.controller.test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.ModelAndViewAssert;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import ec.europa.eu.nwi.web.controller.AvailibilityController;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:spring-servlet.xml"})
public final class AvalibilityControllerTest {
private transient MockHttpServletRequest request;
private transient MockHttpServletResponse response;
#Autowired
private RequestMappingHandlerAdapter handlerAdapter;
#Autowired
private RequestMappingHandlerMapping handlerMapping;
private static final Logger LOGGER = LoggerFactory.getLogger(AvalibilityControllerTest.class);
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
#After
public void tearDown() throws Exception {
LOGGER.debug("TearDown");
}
#Test
public void testAvailable() {
LOGGER.debug("Start testAvailable1");
LOGGER.debug("Test only availibility of the apps");
final AvailibilityController avc = new AvailibilityController();
final Object mav = avc.available(request);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(mav instanceof ModelAndView);
ModelAndViewAssert.assertAndReturnModelAttributeOfType((ModelAndView)mav, "sample", String.class);
ModelAndViewAssert.assertModelAttributeAvailable((ModelAndView)mav, "sample");
ModelAndViewAssert.assertModelAttributeValue((ModelAndView)mav, "sample", "availability on 0.0.1");
ModelAndViewAssert.assertViewName((ModelAndView)mav, "available");
final BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
LOGGER.debug("End testAvailable1");
}
#Test
public void testAvailable1() throws Exception {
LOGGER.debug("Start testAvailable");
LOGGER.debug("Test only availibility of the apps");
request.setMethod("GET");
request.setRequestURI("/available.html");
Object handler = handlerMapping.getHandler(request).getHandler();
LOGGER.debug("Get the Model and View");
ModelAndView modelAndView = handlerAdapter.handle(request, response,handler);
Assert.assertEquals("availability on 0.0.1", modelAndView.getModel().get("sample"));
Assert.assertTrue(modelAndView.getModel().containsKey("sample"));
LOGGER.debug("End testAvailable");
}
}
If I run with JUnit (Run As Junit), all is right but when I run Cover As .. JUnit I receive the error.
The error :
I filtered the class (from exclude configuration in Eclipse Coverage Configuration).
If I removed the filter, the junit code is marked in red
I don't understand the error.
Thanks a lot

I had
<aop:aspectj-autoproxy proxy-target-class="true" />
In my applicationContext.xml and it is running fine now
Thanks a lot

Related

AEM MockitoJUnitRunner using powermockito for testing components using WCMUsePojo for aemcontext

i am referring the link https://www.exadel.com/news/aem-tip-junit-tests-for-wcmusepojo-objects/
I am working on adding the abstract
Below the code is not resolving in IDE
component = PowerMockito.mock(componentClass);
any inputs as what could be the reason and how to resolve it
import org.apache.poi.ss.formula.functions.T;
import org.powermock.api.mockito.PowerMockito;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
protected T component;
protected final Class componentClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
component = PowerMockito.mock(componentClass);
========================================================
>>Please provide inputs
Below is the actual class i added and it showing errors in ide
import com.adobe.cq.sightly.SightlyWCMMode;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.poi.ss.formula.functions.T;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo;
import org.junit.Before;
import org.powermock.api.mockito.PowerMockito;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import static org.powermock.api.mockito.PowerMockito.when;
public abstract class AbstractComponenPowerJuTest {
protected T component;
protected ValueMap valueMap;
protected SlingScriptHelper slingScriptHelper;
protected SlingHttpServletRequest slingHttpServletRequest;
protected ResourceResolver resourceResolver;
protected SightlyWCMMode sightlyWCMMode;
protected Resource resource;
protected MockRequestPathInfo requestPathInfo;
private boolean firstRun = true;
protected final Class componentClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
protected final AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);
protected void runOnceBeforeTests() {}
#Before
public void setUp() throws Exception {
runOnce();
component = PowerMockito.mock(componentClass);
resource = PowerMockito.mock(Resource.class);
resourceResolver = context.resourceResolver();
valueMap = new ValueMapDecorator(new HashMap<>());
slingScriptHelper = PowerMockito.mock(SlingScriptHelper.class);
slingHttpServletRequest = PowerMockito.mock(SlingHttpServletRequest.class);
sightlyWCMMode = PowerMockito.mock(SightlyWCMMode.class);
when(component.getResource()).thenReturn(resource);
when(resource.getResourceResolver()).thenReturn(resourceResolver);
when(component.getResourceResolver()).thenReturn(resourceResolver);
when(component.getProperties()).thenReturn(valueMap);
when(component.getSlingScriptHelper()).thenReturn(slingScriptHelper);
when(component.getRequest()).thenReturn(slingHttpServletRequest);
when(component.getWcmMode()).thenReturn(sightlyWCMMode);
requestPathInfo = new MockRequestPathInfo();
when(slingHttpServletRequest.getRequestPathInfo()).thenReturn(requestPathInfo);
when(slingHttpServletRequest.getResourceResolver()).thenReturn(resourceResolver);
}
private void runOnce() {
if (firstRun) {
firstRun = false;
runOnceBeforeTests();
}
}
}
}

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

junit test cases using embed mongodb de.flapdoodle.embed.mongo

I wanted to setup mongodb junit environment with flapdoodle and I got a java.io.IOException when it tries to download the mongodb archive.
I am using:
spring-data-mongodb: 1.6.1.RELEASE
de.flapdoodle.embed.mongo 1.47.3
org.springframework: 4.0.3.RELEASE
I am getting following error:
de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://downloads.mongodb.org/win32/mongodb-win32-i386-3.0.2.zip
Caused by: java.net.UnknownHostException: downloads.mongodb.org
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
and also its pointing to mongodb-win32-i386-3.0.2.zip but I am using windows 64 bit.
here is my code
package com.bosch.test;
import junit.framework.TestCase;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.bosch.in.model.Device;
import com.bosch.in.service.imp.DeviceServiceImp;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
#ContextConfiguration(classes=ApplicationConfig.class,loader=AnnotationConfigContextLoader.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class DeviceServiceTest2 {
private static final MongodStarter starter = MongodStarter
.getDefaultInstance();
private static MongodExecutable mongodExe;
private static MongodProcess mongod;
private static MongoClient mongo;
private DeviceServiceImp deviceServiceImp;
private MongoTemplate template;
#BeforeClass
public static void setUp() throws Exception {
//System.out.println("1");
mongodExe = starter.prepare(new MongodConfigBuilder()
.version(Version.Main.V3_0)
.net(new Net(12345, Network.localhostIsIPv6())).build());
System.out.println("2");
mongod = mongodExe.start();
System.out.println("3");
System.out.println("4");
mongo = new MongoClient("12345", 12345);
System.out.println("5");
}
#AfterClass
public static void tearDown() throws Exception {
mongod.stop();
mongodExe.stop();
}
public Mongo getMongo() {
return mongo;
}
#Test
public void save(){
System.out.println("1");
}
}
I think the problem is that you are using a default MongodStarter that is not aware of your proxy configuration (it was my case).
You just need to configure the mongodStarter.
Instead of using
private static final MongodStarter starter = MongodStarter
.getDefaultInstance();
you should have somthing like this in setUp()
Command command = Command.MongoD;
IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
.defaults(command)
.artifactStore(new ArtifactStoreBuilder()
.defaults(command)
.download(new DownloadConfigBuilder()
.defaultsForCommand(command)
.proxyFactory(new HttpProxyFactory("proxy_host", 8080))))
.build();
MongodStarter starter = MongodStarter.getInstance(runtimeConfig);
This configuration is well explained on flapdoodle doc.

Using Testng in Eclipse Juno

I am using Eclipse Juno. I installed TestNG plugins properly. But when I want to run test I can't find a TestNG option in Run As. What's the matter?
My Class is
package com.oasisdigital.rental.client;
import static javax.ws.rs.core.Response.Status.CREATED;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import javax.ws.rs.core.Response;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.oasisdigital.rental.test.AbstractIT;
#Test
public class ClientResourceIT extends AbstractIT {
private ClientApi clientApi;
#Override
#BeforeMethod
public void setUp() {
super.setUp();
this.clientApi = new ClientApi(api);
}
#Test
public void shouldReturnEmptyListWhenNoProviders() {
assertThat(clientApi.getClients(), is(empty()));
}
#Test
public void shouldReturnClientAfterCreation() {
Response resp = clientApi.postClient("Jimmy");
assertThat(resp.getStatus(), is(CREATED.getStatusCode()));
ClientDto client = resp.readEntity(ClientDto.class);
assertThat(client.getId(), is(notNullValue()));
assertThat(client.getName(), is("Jimmy"));
assertThat(clientApi.getClients(), contains(client));
}
}

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).