Feign Client with Spring Cloud GatewayFilter cause cycle dependency - spring-boot

During certain checks, I need to make a request to my Microservice in the Gateway Filter.
When I define the Feign class in the GatewayFilter(my SecurityFilter.java) class, it gives the following error.
How can I resolve this situation.
Error:
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| securityFilter defined in file [/target/classes/com/example/SecurityFilter.class]
↑ ↓
| cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
↑ ↓
| routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
└─────┘
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
GatewayFilter class
#Component
public class SecurityFilter implements GatewayFilterFactory<SecurityFilter.Config> {
private final UserApi userApi;
public SecurityFilter(UserApi userApi) {
this.userApi = userApi;
}
#Override
public GatewayFilter apply(Config config) {
return ((exchange, chain) -> {
return chain.filter(exchange.mutate().request(exchange.getRequest()).build());
});
}
#Override
public Class<Config> getConfigClass() {
return Config.class;
}
#Override
public Config newConfig() {
Config c = new Config();
return c;
}
public static class Config {
}
}
pom.xml
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Main class
#SpringBootApplication
#ComponentScan("com.example")
#EnableFeignClients(basePackages = {"com.example.feign"})
public class GatewayApplicationMain {
public static void main(String[] args) {
SpringApplication.run(GatewayApplicationMain.class, args);
}
}
Feign api class
#FeignClient(name = "user", path="userService/", url="http://localhost:8091/")
public interface UserApi {
#GetMapping("/getUserByUserName/{userName}")
ResponseEntity<Object> getUserByUserName(#PathVariable(name = "userName") String userName);
}
Security class
#Configuration
public class SecurityConfig {
#Bean
public SecurityWebFilterChain configure(ServerHttpSecurity http) {
http.csrf().disable()
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login()
.and().oauth2ResourceServer().jwt();
return http.build();
}
}
application.properties file
server.port=8090
spring.main.allow-circular-references=true

private final UserApi userApi;
#Autowired
public SecurityFilter(#Lazy UserApi userApi) {
this.userApi = userApi;
}
This is how I was able to fix the problem by adding #Lazy.

If you intend to keep the circular dependency you can add this configuration
spring.main.allow-circular-references: true

I'm using #Lazy annotation whenever the feign client intent to be use, to avoid Circular Reference Error when using spring-cloud-gateway along with OpenFeign, even in my CustomGatewayFilter :)
#Component
public class CustomApiGatewayFilter extends AbstractGatewayFilterFactory<CustomApiGatewayFilter.Config> {
private static Logger logger = LogManager.getLogger(CustomApiGatewayFilter.class);
private final JwtConfig jwtConfig;
private final ThirdPartyFeignClientService thirdPartyFeignClientService;
public CustomApiGatewayFilter(JwtConfig jwtConfig, #Lazy ThirdPartyFeignClientService thirdPartyFeignClientService) {
super(Config.class);
this.jwtConfig = jwtConfig;
this.thirdPartyFeignClientService = thirdPartyFeignClientService;
}
....
....
}
And the usage of this feign client placed on a separate function used by this filter
private String validateToken(String jwtToken) throws MyAppException {
String json = "";
ObjectMapper mapper = new ObjectMapper();
try {
Claims claims = jwtConfig.getAllClaimsFromToken(jwtToken);
String additionalInfo = (String) claims.get("additionalInfo");
JwtPayload payload = mapper.readValue(additionalInfo, JwtPayload.class);
String username = jwtConfig.getUsernameFromToken(jwtToken);
if(thirdPartyFeignClientService.validateClient(payload.getClientId(), payload.getClientSecret())){
return username;
}else{
throw new MyAppException("Invalid Client", ErrorCode.GENERIC_FAILURE);
}
} catch (ExpiredJwtException e) {
logger.error(e.getMessage());
throw new MyAppException(e.getMessage(), ErrorCode.GENERIC_FAILURE);
} catch (Exception e) {
logger.error("Other Exception :" + e);
throw new MyAppException (e.getMessage(), ErrorCode.GENERIC_FAILURE);
}
}
And it works :)

Related

Spring Boot - connect resource server to Spring Session with an Redis server

For evaluation purposes we would like to use Spring Session in combination with an Embedded-Redis server.
When using Spring Boot 2.6.7 with JDK17 we start the Spring Session with an Embedded-Redis server. The server is started just after the 'UI' server. The code and config is given at the end.
The 'resource' server that is receiving the Spring Session token cannot connect to redis.
The resource server code is:
#SpringBootApplication
#RestController
public class ResourceApplication extends WebSecurityConfigurerAdapter {
private final static Logger logger = LoggerFactory.getLogger(ResourceApplication.class);
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests().anyRequest().authenticated();
}
#RequestMapping("/")
#CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = { "x-auth-token", "x-requested-with", "x-xsrf-token" })
public Message home() {
logger.info( "ResourceServer: home()");
return new Message("Hello World");
}
#Bean
HeaderHttpSessionStrategy sessionStrategy() {
return new HeaderHttpSessionStrategy();
}
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
}
The properties are:
security.sessions=NEVER
spring.session.store-type=redis
spring.redis.host=localhost
spring.redis.port=6379
The dependencies are:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
When adding e.g. the spring-session-data-redis
The error message is:
An attempt was made to call a method that does not exist. The attempt
was made from the following location:
org.springframework.boot.autoconfigure.session.RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.customize(RedisSessionConfiguration.java:80)
When adding the spring-sessions-data-redis dependency, gives the same error message.
Only for your information, starting up the Redis-embedded server goes like this:
#SpringBootApplication
#EnableWebSecurity
public class DemoApplication {
private Logger logger = LoggerFactory.getLogger(getClass());
private RedisServer redisServer;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#PostConstruct
public void startRedis() throws IOException {
try {
redisServer = RedisServer.builder().setting("maxheap 256Mb").port(6379).build();
redisServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#PreDestroy
public void stopRedis(){
redisServer.stop();
}
}
Dependencies:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.7.3</version>
</dependency>
The resources:
spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379
spring.session.store-type=redis

AspectJ (Spring) + how to add the embedding of an aspect in a private method and get the specified data

I have created an aspect that should embed logging on methods marked with an annotation and with the private modifier.
In addition, I would like to add information to the log that will be available at the time of execution of the method (for example, the object with which the method works and the name of the method and the class with which it is currently working).
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.9</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
UserController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping
public List<User> getUsers() {
List<User> userList = getUsersInternal();
return userList;
}
#AuditAnnotation()
private List<User> getUsersInternal() {
List<User> allUsers = userService.getAllUsers();
return allUsers;
}
}
annotation
#Retention(RUNTIME)
#Target(METHOD)
#Documented
public #interface AuditAnnotation {
public String nameMethod() default "";
}
loggingService
public interface LoggingService {
void log(String message);
}
/**
* A dummy implementation of logging service,
* just to inject it in {#link com.aspectj.in.spring.boot.aop.aspect.auditlog.interceptor.LoggingInterceptorAspect}
* that's managed by AspectJ
*/
#Service
public class DefaultLoggingService implements LoggingService {
private static final Logger logger = LoggerFactory.getLogger("sample-spring-aspectj");
#Override
public void log(String message) {
logger.info(message);
}
}
aspect
#Aspect
#Component
public class LoggingInterceptorAspect {
#Autowired
private LoggingService loggingService;
#Pointcut("execution(private * *(..))")
public void privateMethod() {}
#Pointcut("#annotation(com.aspectj.in.spring.boot.aop.aspect.auditlog.annotation.AuditAnnotation)")
public void annotatedMethodCustom() {}
#Before("annotatedMethodCustom() && privateMethod()")
public void addCommandDetailsToMessage() throws Throwable {
ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
String message = String.format("User controller getUsers method called at %s", dateTime);
System.out.println("+++++++++++++++++++++++++");
loggingService.log(message);
}
}
configuratinAspect
#Configuration
public class LoggingInterceptorConfig {
#Bean
public LoggingInterceptorAspect getAutowireCapableLoggingInterceptor() {
return Aspects.aspectOf(LoggingInterceptorAspect.class);
}
}
test
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AspectjInSpringBootApplicationTests {
#Autowired
protected TestRestTemplate testRestTemplate;
}
class UserControllerTest extends AspectjInSpringBootApplicationTests {
#Test
void getUsers() {
String url = "/v1/users";
ParameterizedTypeReference<List<User>> typeReference =
new ParameterizedTypeReference<>() {
};
ResponseEntity<List<User>> responseEntity =
testRestTemplate.exchange(url, HttpMethod.GET, null, typeReference);
HttpStatus statusCode = responseEntity.getStatusCode();
assertThat(statusCode, is(HttpStatus.OK));
List<User> employeeDtoList = responseEntity.getBody();
System.out.println(employeeDtoList);
}
}
But at the moment I have no errors .
so far, I see that the aspect is embedded,
but I want it to be detailed so that the aspect is universal and I would not have to explicitly specify in the message in which class it works.
Maybe someone has ideas on how to fix it.
I suggest you to explore the AspectJ documentation and the JoinPoint API, too. Here is a little example in stand-alone AspectJ without Spring. You can adjust it to your needs:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
Application application = new Application();
System.out.println(application.add(4, application.multiply(2, 3)));
application.divide(5, 0);
}
private int add(int i, int j) {
return i + j;
}
private int multiply(int i, int j) {
return i * j;
}
private double divide(int i, int j) {
return i / j;
}
}
package de.scrum_master.aspect;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class MyAspect {
#Before("execution(private * *(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println(joinPoint);
System.out.println(" Signature: " + joinPoint.getSignature());
System.out.println(" Target: " + joinPoint.getTarget());
System.out.println(" Arguments: " + Arrays.deepToString(joinPoint.getArgs()));
}
#AfterReturning(pointcut = "execution(private * *(..))", returning = "result")
public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
System.out.println(" Result: " + result);
}
#AfterThrowing(pointcut = "execution(private * *(..))", throwing = "exception")
public void afterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
System.out.println(" Exception: " + exception);
}
}
Console log:
Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
execution(int de.scrum_master.app.Application.multiply(int, int))
Signature: int de.scrum_master.app.Application.multiply(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [2, 3]
Result: 6
execution(int de.scrum_master.app.Application.add(int, int))
Signature: int de.scrum_master.app.Application.add(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [4, 6]
Result: 10
10
execution(double de.scrum_master.app.Application.divide(int, int))
Signature: double de.scrum_master.app.Application.divide(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [5, 0]
Exception: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
at de.scrum_master.app.Application.divide(Application.java:19)
at de.scrum_master.app.Application.main(Application.java:7)
In addition to the context data I printed here, you can also get annotations and their properties, method parameter names (even though I think that is unnecessary and availability depends on compilation options) etc.

JavaFX 12 maven and Spring

I'm trying to add spring to my pom
but I'm wondering if my build will look like this.
Could someone help me how can I do this spring integration with java fx?
my pom:
<properties>
<java.version>12</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
main class:
public class App extends Application {
private static Scene scene;
#Override
public void start(Stage stage) throws IOException {
scene = new Scene(loadFXML("primary"));
stage.setScene(scene);
stage.show();
}
static void setRoot(String fxml) throws IOException {
scene.setRoot(loadFXML(fxml));
}
private static Parent loadFXML(String fxml) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
return fxmlLoader.load();
}
public static void main(String[] args) {
launch();
} }
I searched and found nothing about integrating javafx with spring
Could someone help me how I can integrate spring?
I tried to use what I used in my swing project but it didn't work out
Your main app has to maintain Spring's application context like this.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
#Configuration // or #SpringBootApplication if you used spring boot.
public class App extends Application {
private static Scene scene;
private AbstractApplicationContext context;
#Override
public void init() throws Exception {
this.context = new AnnotationConfigApplicationContext(App.class);
super.init();
}
#Override
public void start(Stage stage) throws IOException {
SpringFxmlLoader loader = new SpringFxmlLoader(this.context);
Parent root = loader.loadFromResource("primary.fxml");
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
use SpringFxmlLoader for returning a controller as a spring bean.
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.springframework.context.ApplicationContext;
import javafx.fxml.FXMLLoader;
public class SpringFxmlLoader extends FXMLLoader {
private ApplicationContext context;
protected SpringFxmlLoader() {
}
public SpringFxmlLoader(ApplicationContext context) {
this.context = context;
setControllerFactory(context::getBean); // return a spring bean from spring's application context.
}
public ApplicationContext getContext() {
return this.context;
}
public <T> T loadFromResource(String resource) throws IOException {
return loadFromResource(resource, null);
}
public <T> T loadFromResource(String resource, Class<?> root) throws IOException {
URL resourceURL = context.getResource(resource).getURL();
setLocation(resourceURL);
if(root != null) setRoot(root);
try (InputStream fxml = resourceURL.openStream()) {
return load(fxml);
}
}
}
Your controller should be looked like this as a spring bean.
#Controller
#Scope("prototype")
public class PrimaryController {
#FXML private Parent rootView;
#FXML private TitledPane settingPane;
#Autowired private SomeBean someBean; // now you can autowire spring beans.
// braa....
}
Don't forget specify the controller class in your primary.fxml with fx:controller attribute.

Spring annotation gives null value in my Spring MVC when I create JAX-RS Web service

I added JAX-RS Web service for my project .I want to get XML file. It works fine when I hard cord something on return statement and it works fine. But I want to get data from my database. I use
#Autowired
private ProductServices productServices;
for call Spring Service class... For other normal controllers this #Autowired working fine. In JAX-RS it doesn't works.
JAX-RS gives null value like this
I want to call this service for get data to my method. How can I do that..
This is my Model.
#Entity
#Table(name = "products")
#XmlRootElement
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "product_id")
private long productId;
#NotNull
private String serialNo;
#NotNull
private int slsiUnit;
#NotNull
private String itemDesc;
#NotNull
private int slsNo;
#NotNull
private String hsCode;
#NotNull
private String userIDandTime;
#NotNull
private String recentUpdateBy;
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getSerialNo() {
return serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public int getSlsiUnit() {
return slsiUnit;
}
public void setSlsiUnit(int slsiUnit) {
this.slsiUnit = slsiUnit;
}
public String getItemDesc() {
return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
public int getSlsNo() {
return slsNo;
}
public void setSlsNo(int slsNo) {
this.slsNo = slsNo;
}
public String getHsCode() {
return hsCode;
}
public void setHsCode(String hsCode) {
this.hsCode = hsCode;
}
public String getUserIDandTime() {
return userIDandTime;
}
public void setUserIDandTime(String userIDandTime) {
this.userIDandTime = userIDandTime;
}
public String getRecentUpdateBy() {
return recentUpdateBy;
}
public void setRecentUpdateBy(String recentUpdateBy) {
this.recentUpdateBy = recentUpdateBy;
}
}
This is my Repository.
public interface ProductRepository extends CrudRepository<Product, Long> {
#Override
Product save(Product product);
#Override
Product findOne(Long productId);
#Override
List<Product> findAll();
#Override
void delete(Long productId);
}
This is my Services class
#Service
public class ProductServices {
private static final Logger serviceLogger = LogManager.getLogger(ProductServices.class);
#Autowired
private ProductRepository productRepository;
public List<Product> getProductList() {
return productRepository.findAll();
}
public Product getProductById(long productId) {
return productRepository.findOne(productId);
}
}
This is my JAX-RS Web Service class
#Path("release")
public class GenericResource {
#Context
private UriInfo context;
#Autowired
private ProductServices productServices;
public GenericResource() {
}
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Product> getXml() {
List<Product> a = productServices.getProductList();
return a;
}
}
This is the MessageBodyWriter
#Provider
#Produces(MediaType.APPLICATION_XML)
public class restConverter implements MessageBodyWriter<List<Product>> {
#Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Product.class.isAssignableFrom(type);
}
#Override
public long getSize(List<Product> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
#Override
public void writeTo(List<Product> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
out.write(t.toString().getBytes());
}
}
This is a extend class for JSX-RS
#ApplicationPath("TransferPermit/Slsi_Customs/restAPI")
public class restConfig extends Application{
}
This is my pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--handle servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--<Email Dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<!--Add mysql dependency-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!--jasper-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<type>jar</type>
</dependency>
</dependencies>
Special : This cord works fine. But in Web service class productServices auto-wired dependency not working. What is the error :
#RequestMapping(value = "/ViewProduct", produces = {MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.GET)
#JsonIgnore
public ResponseEntity<List<Product>> listAllProducts() {
List<Product> viewProducts = productServices.getProductList();
if (viewProducts.isEmpty()) {
return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
}
System.out.println("entity " + new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT));
return new ResponseEntity<List<Product>>(viewProducts, HttpStatus.OK);
}
What is the error in my cord. How can I call data from database
Please help me someone for return XML...

Spring boot - configure EntityManager

I was using Google guice in my project and now I tried to convert the framework to SpringBoot totally.
I configured the Bean for persistence.xml like below in
#Autowired
#Bean(name = "transactionManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean lEMF = new LocalContainerEntityManagerFactoryBean();
lEMF.setPersistenceUnitName("leaseManagementPU");
lEMF.setPersistenceXmlLocation("persistence.xml");
return lEMF;
}
Now I need to configure(Inject) EntityManager em, to do JPA operations like em.persist(), em.find etc... How do I configure, also someone try to explain this with sample code
With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the
application.properties
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.
#Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
And if you still need to use the Entity Manager you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
#PersistenceContext
private EntityManager em;
}
This should be in your pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
#Configuration
#Import({PersistenceConfig.class})
#ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
PersistenceConfig
#Configuration
#PropertySource(value = { "classpath:database/jdbc.properties" })
#EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
#Autowired
private Environment env;
#Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
Main
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
MyService
#Service
public class MyServiceImpl implements MyService {
#Inject
private MyDao myDao;
#Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
MyDaoImpl
#Repository
#Transactional
public class MyDaoImpl implements MyDao {
#PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database folder
jdbc.properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
a.b.c.entities.Student
//dummy class and dummy query
#Entity
#NamedQueries({
#NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
a.b.c.converters
#Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
pom.xml
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks

Resources