org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'locationController': Unsatisfied
dependency expressed through field 'locationRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'locationRepository' defined in
com.abunyc.location.repository.LocationRepository defined in
#EnableJpaRepositories declared on
JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Validation failed for query for
method public abstract java.util.List
com.abunyc.location.repository.LocationRepository.findTypeAndCount()!
ReportUtil.java
package com.abunyc.location.util;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
public interface ReportUtil {
void generatePieChart(String path, List<Object[]> data );
}
ReportUtilImpl.java
package com.abunyc.location.util;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.stereotype.Component;
#Component
public class ReportUtilImpl implements ReportUtil {
#Override
public void generatePieChart(String path, List<Object[]> data) {
DefaultPieDataset dataset = new DefaultPieDataset();
for (Object[] objects : data) {
dataset.setValue(objects[0].toString(), new Double(objects[1].toString()));
}
JFreeChart chart = ChartFactory.createPieChart3D("Location Type Report", dataset);
try {
ChartUtilities.saveChartAsJPEG(new File(path + "/pieChart.jpeg"), chart, 300, 300);
} catch (IOException e) {
e.printStackTrace();
}
}
}
LocationReportory.java##
package com.abunyc.location.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.abunyc.location.entities.Location;
/**
* #author Abu
*/
#Repository
public interface LocationRepository extends JpaRepository<Location, Integer> {
#Query("select type, count(type) from location_tbl group by type")
public List<Object[]> findTypeAndCount();
}
LocationController.java
package com.abunyc.location.controller;
import java.util.List;
import java.util.Optional;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.abunyc.location.entities.Location;
import com.abunyc.location.repository.LocationRepository;
import com.abunyc.location.service.LocationService;
import com.abunyc.location.util.EmailUtil;
import com.abunyc.location.util.ReportUtil;
/**
* #author Abu
*/
#Controller
public class LocationController {
#Autowired
LocationRepository locationRepository;
#Autowired
LocationService locationService;
#Autowired
EmailUtil emailUtil;
#Autowired
ReportUtil reportUtil;
#Autowired
ServletContext servletContext;
#RequestMapping("/showCreate")
public String showCreate() {
return "createLocation";
}
#RequestMapping(value = "/saveLoc", method = RequestMethod.POST)
public String saveLocation(#ModelAttribute("location") Location location, ModelMap modelMap) {
Location locationSaved = locationService.createLocation(location);
String msg = "Location Saved with id " + locationSaved.getId();
modelMap.addAttribute("successMsg", msg);
//Email calls to send email.
emailUtil.sendEmail("codeexample7#gmail.com", "Location Saved",
"Location Saved successfully and success response was returned to the calling page");
return "createLocation";
}
#RequestMapping("/displayLocation")
public String displayLocation(ModelMap modelMap) {
List<Location> locations = locationService.getAllLocation();
modelMap.addAttribute("locations", locations);
return "displayLocation";
}
#RequestMapping("/deleteLocation")
public String deleteLocation(#RequestParam("id") int id, ModelMap modelMap) {
Location location = new Location();
location.setId(id);
locationService.deleteLocation(location);
// Reloading with all remaining datas
List<Location> locations = locationService.getAllLocation();
modelMap.addAttribute("locations", locations);
return "displayLocation";
}
#RequestMapping("/showUpdate")
public String showUpdateLocation(#RequestParam("id") int id, ModelMap modelMap) {
Optional<Location> location = locationService.getLocationById(id);
if (location.isPresent()) {
Location locationUpdate = location.get();
modelMap.addAttribute("location", locationUpdate);
}
return "updateLocation";
}
#RequestMapping("/updateLoc")
public String updateLocation(#ModelAttribute("location") Location location, ModelMap modelMap) {
locationService.updateLocation(location);
List<Location> aLllocation = locationService.getAllLocation();
modelMap.addAttribute("locations", aLllocation);
return "displayLocation";
}
#RequestMapping("/generateReport")
public String generateReport() {
List<Object[]> data = locationRepository.findTypeAndCount();
String path = servletContext.getRealPath("/");
reportUtil.generatePieChart(path, data);
return "report";
}
}
Related
I'm using redis in my springboot rest application to store cache. But the problem I'm facing is once it is stored in redis my api only hits the redis not the database. I've added time out property it didn't work. I've tried CacheManager to get the cache and call CacheEvict to clear the cache and then CachePut to put the data again, but it didn't work. These are the things I've tried so far. I wanted my redis cache to refresh after a given time set by me. Any advice on this? Here is my code below:
package com.dg.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.dg.entity.FlightEntity;
public interface FlightRepo extends JpaRepository<FlightEntity, String> {
#Query(value="select distinct txtFlightName\r\n"
+ "from {test-schema}flights", nativeQuery = true)
List<String> getAllFlights();
#Query(value="select distinct txtFlightName from {test-schema}flights \r\n"
+ "where txtFlightName LIKE %:flightname%",nativeQuery = true)
List<String> getListofFlights(#Param("flightname")String flightname);
#Query(value="select distinct txtBookingCode,txtFlightName from {test-schema}flights \r\n"
+ "where txtFlightName LIKE %:flightname%",nativeQuery = true)
List<FlightEntity> getFlightEntity(#Param("flightname")String flightname);
}
package com.dg.repo;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;
import com.dg.entity.FlightEntity;
public abstract class FlightRepoImpl implements FlightRepo {
RedisTemplate template;
HashOperations hashOperations;
public FlightRepoImpl(RedisTemplate template, HashOperations hashOperations) {
super();
this.template = template;
this.hashOperations = template.opsForHash();
}
#Override
public List<String> getAllFlights() {
return hashOperations.values("FlightModel");
}
#Override
public List<String> getListofFlights(String flightname) {
return (List<String>) hashOperations.get("FlightModel", flightname);
}
}
package com.dg.service;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import com.dg.model.FlightModel;
import com.dg.repo.FlightRepo;
public class FlightService {
#Autowired
FlightRepo flightRepo;
#Autowired
ModelMapper modelMapper;
#Scheduled(fixedRate = 50000)
#Caching(evict = {#CacheEvict(value="getFlightList", key="#flightname")})
public FlightModel getFlightByFlightName(String flightName)
{
package com.dg.model;
import java.io.Serializable;
import java.util.List;
public class FlightModel implements Serializable{
private List<Object> listofflightname;
public List<Object> getListofflightname() {
return listofflightname;
}
public void setListofflightname(List<Object> listofflightname) {
this.listofflightname = listofflightname;
}
}
package com.dg.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class FlightEntity {
#Id
#Column(name="txtBookingCode")
private String bookingCode;
#Column(name="txtFlightName")
private String flightname;
public String getBookingCode() {
return bookingCode;
}
public void setBookingCode(String bookingCode) {
this.bookingCode = bookingCode;
}
public String getFlightname() {
return flightname;
}
public void setFlightname(String flightname) {
this.flightname = flightname;
}
}
package com.dg.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import redis.clients.jedis.JedisPoolConfig;
#Configuration
#EnableRedisRepositories
#Profile("test")
public class RedisConfig {
#Value("${spring.redis.cluster.nodes}")
private String nodesProperty;
#Bean
public JedisConnectionFactory jedisConnectionFactory()
{
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMinIdle(2);
poolConfig.setMaxIdle(5);
poolConfig.setMaxTotal(20);
poolConfig.setEvictorShutdownTimeoutMillis(10000);
String [] nodesArray=nodesProperty.split(",");
List<String> nodes = new ArrayList<String>(Arrays.asList(nodesArray));
RedisClusterConfiguration configuration=new RedisClusterConfiguration(nodes);
configuration.setMaxRedirects(100);
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration);
connectionFactory.setPoolConfig(poolConfig);
return connectionFactory;
}
#Bean
public RedisTemplate redisTemplate()
{
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
package com.dg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
#SpringBootApplication
#EnableCaching
public class RedisTestApplication {
public static void main(String[] args) {
SpringApplication.run(RedisTestApplication.class, args);
}
}
Hi I am new to spring and have created an Export csv application with two controllers which can give all the data as well as selective columns data and want to write junits for the same but it is quite difficult for me to do the same as I am not aware how i should do it some help would be really great
Main class:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
import net.bytebuddy.implementation.bind.annotation.Super;
#SpringBootApplication
public class ExampleApplication implements CommandLineRunner {
#Autowired
ExampleRepository exampleRepository;
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Example> example= new ArrayList<>();
// create dummy
example.add(new Example(1,"abc","sachin","abc","abc"));
example.add(new Example(2,"abc","rahul","abc","abc"));
example.add(new Example(3,"abc","rahul","abc","abc"));
exampleRepository.saveAll(example);
}
}
Entity layer:
package com.example.model;
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="example")
public class Example{
#Column(name="city")
private String city;
#Column(name="name")
private String name;
#Column(name="amount")
private String amount;
#Column(name="country")
private String country;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
//getter and setters
}
Repository layer is as follows:
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.model.Example;
#Repository("exampleRepository")
public interface ExampleRepository extends JpaRepository<Example,Long> {
List<Report> findByName(String name);
}
service layer is as follows
package com.example.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
#Transactional
#Service
public class ExampleService {
#Autowired
ExampleRepository exampleRepository;
public List<Example> fetchAll() {
return exampleRepository.findAll();
}
public List<Example> findByName(String name){
return exampleRepository.findByName(name);
}
}
I have 2 controllers one to get all details and one to get selective columns and here we are generating csv files based on records that match the name
COntroller 1:
package com.example.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/demo")
public class Controller1 {
#Autowired
ExampleService exampleService;
#GetMapping("/result")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "names.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(examplesService.findByName(name));
}
}
Controller 2:
package com.reports.controllers;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/example")
public class Controller2 {
#Autowired
ExampleService exampleService;
#GetMapping("/output")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Example.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())
))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(exampleService.findByname(name));
}
}
Try this approach :
generate a file in your /src/test/resources path and then test if it contains the generated data you expected
use combine it with a file system mocking to do it
You will :
test your ResController
mock your Service class
Also use Contructor Injection for you dependency
I am working on my first Spring-Boot app. Got a working UI Controller implemented below:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.ArrayList;
#Controller
public class UiController {
private ProductService productService;
private LocationService locationService;
private InventoryService inventoryService;
private CartService cartService;
public UiController(
ProductService productService,
LocationService locationService,
InventoryService inventoryService,
CartService cartService) {
this.productService = productService;
this.locationService = locationService;
this.inventoryService = inventoryService;
this.cartService = cartService;
}
#GetMapping("/")
public String home(Model model) {
model.addAttribute("products", productService.getAllProducts());
return "index";
}
#GetMapping("/brand/{brand}")
public String brand(Model model, #PathVariable String brand) {
List prods = productService.getProductByBrand(brand);
if (prods.size() == 0) throw new ItemNotFoundException();
model.addAttribute("products", prods);
return "index";
}
#ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such item") // 404
public class ItemNotFoundException extends RuntimeException {
// ...
}
#GetMapping("/product/{productId}")
public String product(Model model, #PathVariable String productId) {
Product prod = productService.getProduct(productId);
if (prod == null) throw new ItemNotFoundException();
ArrayList<Product> ps = new ArrayList<Product>();
ps.add(prod);
model.addAttribute("products", ps);
return "index";
}
}
I want to add a REST controller returning the same thing as HTML only I want the responses to be in JSON. When there is no data, I want an error return. Added the below:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.Gson;
#ApiController
public class ApiController {
private ProductService productService;
private LocationService locationService;
private InventoryService inventoryService;
private CartService cartService;
public ApiController(
ProductService productService,
LocationService locationService,
InventoryService inventoryService,
CartService cartService) {
this.productService = productService;
this.locationService = locationService;
this.inventoryService = inventoryService;
this.cartService = cartService;
}
#GetMapping("/rest")
public String home() {
List prods = productService.getAllProducts();
if (prods.size() == 0) throw new ItemNotFoundException();
return new Gson().toJson(prods);
}
#GetMapping("/rest/brand/{brand}")
public String brand(#PathVariable String brand) {
List prods = productService.getProductByBrand(brand);
if (prods.size() == 0) throw new ItemNotFoundException();
return new Gson().toJson(prods);
}
#ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such item") // 404
public class ItemNotFoundException extends RuntimeException {
// ...
}
#GetMapping("/rest/product/{productId}")
public String product(#PathVariable String productId) {
Product prod = productService.getProduct(productId);
if (prod == null) throw new ItemNotFoundException();
return new Gson().toJson(prod);
}
}
Apparently, autoconfig is working and my controller gets picked by the compiler. Only, I get the below error:
Compilation failure
ApiController.java:[21,2] incompatible types: com.rei.interview.ui.ApiController cannot be converted to java.lang.annotation.Annotation
What am I doing wrong and what should I do?
You did a simple mistake at the beginning of the controller.
The class must be annotated #RestController... not #ApiController
Change your code from
#ApiController
public class ApiController {
...
}
to
#RestController // <- Change annotation here
public class ApiController {
...
}
The error
ApiController.java:[21,2] incompatible types:
com.rei.interview.ui.ApiController cannot be converted to java.lang.annotation.Annotation
informs you that the annotation #ApiController is not a of type java.lang.annotation.Annotation
I'm trying to persist a cassandra entity but on startup I get:
Caused by: org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class com.service.model.Cart!
This is my entity class:
package com.service.model;
import io.vavr.collection.LinkedHashMap;
import io.vavr.collection.Map;
import lombok.Getter;
import lombok.ToString;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
#ToString
#Table("carts")
public class Cart {
#Getter
#PrimaryKey
private final UUID uuid;
private final Map<CartItemKey, CartItem> items;
public Cart(UUID uuid) {
this(uuid, LinkedHashMap.empty());
}
private Cart(UUID uuid, Map<CartItemKey, CartItem> items) {
this.uuid = Objects.requireNonNull(uuid, "Cart's uuid cannot be null");
this.items = Objects.requireNonNull(items, "Cart's items cannot be null");
}
}
This is my CassandraConfig:
package com.service.configuration;
import com.service.model.Cart;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.cassandra.config.AbstractClusterConfiguration;
import org.springframework.data.cassandra.core.convert.CassandraCustomConversions;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.util.Collections.singletonList;
#Configuration
public class CassandraConfig extends AbstractClusterConfiguration {
#Value("${spring.data.cassandra.keyspace-name}")
private String keyspaceName;
#Value("${spring.data.cassandra.contact-points}")
private String contactPoints;
#Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
return singletonList(
CreateKeyspaceSpecification.createKeyspace(keyspaceName)
.ifNotExists()
.with(KeyspaceOption.DURABLE_WRITES, true)
.withSimpleReplication());
}
#Override
protected boolean getMetricsEnabled() {
return false;
}
#Override
protected String getContactPoints() {
return contactPoints;
}
#Bean
public CassandraCustomConversions customConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(new CartWriteConverter());
converters.add(new CartReadConverter());
return new CassandraCustomConversions(converters);
}
static class CartWriteConverter implements Converter<Cart, String> {
public String convert(Cart source) {
try {
return new ObjectMapper().writeValueAsString(source);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
static class CartReadConverter implements Converter<String, Cart> {
public Cart convert(String source) {
if (StringUtils.hasText(source)) {
try {
return new ObjectMapper().readValue(source, Cart.class);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return null;
}
}
}
And lastly my Application:
package com.service.cart;
import org.axonframework.springboot.autoconfig.AxonServerAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
#EnableCaching
#EnableAsync
#EnableFeignClients
#SpringBootApplication
#EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
AxonServerAutoConfiguration.class})
#EnableCassandraRepositories(basePackages = "com.service.repository")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
What seems puzzling to me is that when I remove customConversions() bean it fails with a different error - not being able to map vavr Map, so spring must have scanned and registered this entity so that it got inspected. This is expected while it is not cassandra data type but in my understanding adding my custom conversions should solve this problem.
I also tried experimenting with #EntityScan with the same results.
Any help would be appreciated.
I am trying to write basic spring project. However, I have a big issue using `#Autowired through the Service. I didn't find the problem and got the error bellow:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blackfirday.services.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 19 common frames omitted
Here is my code:
UserServiceInterface
package com.blackfirday.services;
import com.blackfriday.generated.User;
public interface UserService {
public User userLogin(final String userId, final String userPassword);
}
UserServiceImpl
package com.blackfirday.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.blackfriday.dao.UserDao;
import com.blackfriday.generated.User;
#Service("userService")
public class UserServiceImpl implements UserService {
#Autowired(required=true)
#Qualifier(value="userDao")
private UserDao userDao_;
#Override
public User userLogin(String userId, String userPassword) {
// TODO: Varify the user password in the returned user object.
return userDao_.getUserDetails(userId);
}
}
UserDao Interface
package com.blackfriday.dao;
import com.blackfriday.generated.User;
public interface UserDao {
public User getUserDetails(final String userId);
}
UserDao Impl
package com.blackfriday.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Repository;
import com.blackfriday.generated.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
private final String connectionURL = "jdbc:msql://localhost:3306/blackfridaybank";
private static final String DRIVER_PREFIX = "jdbc:apache:commons:dbcp:";
#Override
public User getUserDetails(String userId) {
// TODO Make the database as centralized connection pool.
Connection conn = null;
User user = new User();
try {
conn = getConnection(connectionURL);
conn.setAutoCommit(true);
Statement stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("select * from user where id="+userId);
while(rs.next()){
user.setUserId(rs.getString("id"));
user.setUserName(rs.getString("name"));
user.setUserGender(rs.getString("gender"));
user.setUserStatus(rs.getString("status"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try{
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return user;
}
private Connection getConnection(final String connectURL) throws SQLException {
return DriverManager.getConnection(DRIVER_PREFIX + connectURL, "blackfriday", "blackfriday");
}
}
UserServicesEndPoint
package com.blackfriday.webservices.endpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.blackfirday.services.UserService;
import com.blackfriday.generated.UserLoginRequest;
import com.blackfriday.generated.UserLoginResponse;
#Endpoint
public class UserServicesEndPoint {
private static final String USER_LOGIN_REQUEST = "http://www.blackfridaybank.org/webservices/UserOperation";
private UserService userService;
#Autowired
public UserServicesEndPoint(UserService userService_i){
userService = userService_i;
}
#PayloadRoot(localPart = "UserLoginRequest", namespace = USER_LOGIN_REQUEST)
#ResponsePayload
public UserLoginResponse getUserDetails(#RequestPayload UserLoginRequest request) {
// 1.we need to make an instance of a response
UserLoginResponse response = new UserLoginResponse();
// 2.use the request data to in the services class and populated to
// response
response.setUserDetails(userService.userLogin(request.getUserId(), request.getPassword()));
// 3.return a data populated response.
return response;
}
}
Startup class
package com.blackfriday.startup;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages={"com.blackfriday"})
public class Startup {
public static void main(String[] args) {
SpringApplication.run(Startup.class, args);
}
}
Web Config
package com.blackfriday.startup;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebSerivceConfig extends WsConfigurerAdapter{
#Bean
public ServletRegistrationBean messageDispatcherServlet (ApplicationContext context) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(context);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name="useroperation")
public DefaultWsdl11Definition defaultWsdl11Definition (XsdSchema UserOperation) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("useroperationport");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.blackfridaybank.org/webservices/UserOperation");
wsdl11Definition.setSchema(UserOperation);
return wsdl11Definition;
}
#Bean
public XsdSchema UserOperation() {
return new SimpleXsdSchema(new ClassPathResource("UserOperation.xsd"));
}
//adding the following method to return the correct xsd file before loaded to the soapui.
#Bean
public XsdSchema UserDetails() {
return new SimpleXsdSchema(new ClassPathResource("UserDetails.xsd"));
}
}