FAQ Database Discussion Community


Spring Data Rest executes query but returns 500 internal Server Error

java,spring,rest,spring-boot,spring-data-rest
I am using spring boot and spring data rest and I am facing a 500 internal server error, but no messages are displayed in console. I have the following: ProdutoVendaRepository.java public interface ProdutoVendaRepository extends PagingAndSortingRepository<ProdutoVenda, Integer> { @Query("SELECT new br.com.contoso.model.VendaPorFamilia(b.nome, SUM(i.valorMultiplicado)) FROM ProdutoVenda i JOIN i.produto o JOIN o.familia b...

Spring: @NestedConfigurationProperty List in @ConfigurationProperties

spring,properties,configuration,spring-boot
Hi I am trying to get the following configuration up and running. @ConfigurationProperties(prefix="my") public class Config { @NestedConfigurationProperty private List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>(); public List<ServerConfiguration> getServers() { return this.servers; } } @ConfigurationProperties(prefix = "server") public class ServerConfiguration { private String name; private String description; } So, I want to...

spring boot rabbitmq MappingJackson2MessageConverter custom object conversion

java,json,rabbitmq,spring-boot,spring-amqp
I'm trying to create a simple spring boot app with spring boot that "produce" messages to a rabbitmq exchange/queue and another sample spring boot app that "consume" these messages. So I have two apps (or microservices if you wish). 1) "producer" microservice 2) "consumer" microservice The "producer" has 2 domain...

Not Able to Resolve View Using Spring boot

spring,spring-mvc,spring-boot
I have put all jsp on classpath in views folder. Folder structure is : src/main/resources/ src/main/resources/static/ src/main/resources/static/views/ src/main/resources/static/views/*.jsp src/main/resources/static/views/*.png I am able to retrieve images file from static folder. But When It comes to jsp I am getting following error. While hitting url:http://localhost:9001/login There was an unexpected error (type=Not Found,...

Can spring boot be told to start an application only if a resource is available?

java,spring,spring-boot,postconstruct
I am part of a team developing a spring boot backend application, which provides mobile applications with data. Along with a new feature the need of loading a resource at the backend, which need to be provided to the mobile application arose. Due to the fact that this resource is...

Spring Boot Actuator Health Returning DOWN

spring-boot
When I access the /health endpoint from my Spring Boot application (1.2.4.RELEASE) it is returning a status of DOWN: { status: "DOWN" } Are there any starter projects or libraries that are known to overwrite the status? Is there any other reason (besides writing a custom one) why it would...

spring-boot without template engine

spring-mvc,spring-boot
I have a Spring-Boot app that is apparently way out of the norm. It's Spring-MVC, but I don't want to use velocity,thymeleaf or anything. Ideally I would just use HTML. Then I use jQuery to make my AJAX calls to my REST services, and then fill in the pages with...

Spring Boot OAuth2 Custom Login Form Use case

spring-boot,spring-security-oauth2
The oauth2 JWT project from the "Getting Started Spring Security and Angular JS Series" has a custom login. Adding the same code for a custom login page to the oauth2-vanilla project fails as the authorization code is always empty in the login response. I also tried porting the Sparklr2 (https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2)...

Deserialize jackson in spring boot

java,json,jackson,spring-boot
I am getting two types of json by calling RestTemplate {"results":[{"testing":{"name":"soham"}},{"testing":{"firstname":"john","lastname":"don"}}]} Now I am parsing data using JsonDeserializer public class CustomJacksonDeserialize extends JsonDeserializer<Activity> { @Override public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, NullPointerException { ObjectMapper objectMapper = new ObjectMapper(); JsonNode actualObj =...

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot
My JUnit test is failing with the following error: "java.lang.IllegalArgumentException: Could not find field [userRepository] of type [null] on target [[email protected]]" Here is the Test class: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = App.class) @WebAppConfiguration @IntegrationTest public class UserResourceTest { @Autowired private UserRepository userRepository; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource...

Spring-boot+JPA EntityManager inject fails

spring,java-ee,jpa,spring-boot,cdi
In my J2EE application I try to use spring-boot and JPA technologies with injection of EntityManager into DAO layer. However, I have some problems... My repository for user CRUD: @Repository public class UserRepositoryImpl implements UserRepository { @PersistenceContext(unitName = "data") private EntityManager entityManager; // and crud methods } My spring-boot application...

set an annotation attribute from an environment variable?

spring,groovy,spring-boot
I'm trying to set an annotation value from an environment variable: @Configuration @ComponentScan @EnableAutoConfiguration @EnableScheduling class Application { @Scheduled(cron = "${DB_CRON}") def void schedule() { ... } public static void main(String... args) { SpringApplication.run(Application, args) } ... } However, I get the following compile time error: Attribute 'cron' should have...

Spring Shell - usage and execution

java,spring,spring-boot,command-line-interface,spring-shell
I want to integrate Spring Shell within a spring boot application. I am able to execute the examples from the official git-repo. But when migrating the example code to my own project that is very very similar to this code, my individual shell is not shown or usable. Instead the...

Spring Boot testing with Spring Security. How does one launch an alternative security config?

java,spring,spring-mvc,spring-security,spring-boot
My spring boot application has an Application class. When I run it (as an application), it launches itself within an embedded servlet container (Tomcat, in my case). Somehow (through Application's @annotations, I suppose), WebSecurityConfig (extending WebSecurityConfigurerAdapter) in the same package is loaded. WebSecurityConfig contains two important blocks of configuration information:...

LoggerFactory is not a Logback LoggerContext but Logback is on the classpath

java,logging,spring-security,spring-boot,dependency-management
I think some module in spring-boot-starter-security is conflict with log4j, but I don't know which one. my gradle dependence is as following: compile("org.springframework.boot:spring-boot-starter-thymeleaf") compile("org.springframework.boot:spring-boot-starter-security"){ exclude module: "spring-boot-starter-logging" } compile "org.apache.logging.log4j:log4j-api" compile "org.apache.logging.log4j:log4j-core" compile "org.apache.logging.log4j:log4j-slf4j-impl" compile('org.apache.poi:poi:3.10.1')...

What is the best way to @Conditional on the inclusion of the actuator feature?

spring-boot
I'd like to make some of our auto configurations classes conditional on the presence of the SpringBoot actuator feature on the classpath. Against which class should I write my @ConditionalOnClass annotation? Possible candidates are: org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration org.springframework.boot.actuate.endpoint.EndPoint ...

Cucumber Test a Spring Boot Application

java,spring,spring-boot,cucumber-jvm
Does anyone know where I can find a sample application where Cucumber is used to test a Spring Boot application through Gradle? I can run the tests fine starting the server on the cmd line and using my IDE, but I need to be able to run them all programmatically...

How to not-abbreviate the source class name in spriing-boot's loggger name?

log4j,spring-boot
When I run a spring-boot application, it shows the following log: 2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] The logger name is abbreviated for the following: org.springframework.boot.context.embedded.FilterRegistrationBean How can I show the full source class name for it? Thanks!...

Getting a lost Sentinel error message for Redis

redis,spring-boot,spring-data-redis
I am running a spring boot service using spring data redis and here is the following configuration. The service seems to work but I am seeing a stream of Lost Sentinel messages in the logs. The sentinel nodes are reachable form the VM where I am running the service. I...

How to handle form submission in HTML5 + Thymeleaf

html5,forms,spring-boot,thymeleaf
I have to submit a form with around 30 input parameters(text, select, datepicker ). The fields are mapped to two classes. How to map each field to get the value in the controller. HTML: <form id="searchPersonForm" action="#" th:object="${person}" method="post"> <input type="text" class="form-control" id="person_id" th:field="*{person_id}"></input> <input type="text" class="form-control" id="child_id" th:field="*{child_id}"></input> </form>...

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?

java,spring,spring-mvc,spring-boot
I'm working with Java 8 and Spring 1.2.3 to build an application running inside a Tomcat 7 container. I do intercept every single call to my web application using a very simple HandlerInterceptor, that logs the overall time taken to create a response and the return code for every request....

Spring Boot and @ConfigurationProperties

java,spring,spring-boot
I would like (if possible) to use @ConfigurationProperties to create dynamic sized list of POJOs. Please advice whether this is possible. My idea was something like follows (no-args constructors/getter/setters omitted): The property file: my.item[0].prop1=a my.item[0].prop2=b my.item[1].prop1=a my.item[1].prop2=b And the bean which should be populated: @Component @ConfigurationProperties(prefix = "my") public class...

How to deploy a spring boot MVC application in traditional tomcat webapps folder?

java,spring-mvc,tomcat,spring-boot
I created a simple spring mvc application following a springboot springmvc with gradle example. Below is the structure. src/main/java - This is where all the code base is there. src/main/resources - This is where all the resources/templates are there. import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static...

Mixing JdbcTemplate and raw JDBC

spring,spring-boot,spring-data,spring-jdbc
I am experiencing some strange behaviour which I can't easily explain. The following code runs fine: try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate("DELETE FROM product"); } catch (Exception ex) { throw new RuntimeException(ex); } try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate("INSERT INTO...

Springboot REST application should accept and produce both XML and JSON

java,xml,rest,jackson,spring-boot
I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency. <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.5.4</version> </dependency> I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped...

Spring boot war file deploy on Tomcat

tomcat,deployment,spring-boot,war
I use Spring Boot 1.2.4.RELEASE with gs-rest-service source file. I got: 127.0.0.1 - - [18/Jun/2015:09:59:25 +0300] "GET /gs-rest-service-0.1.0/ HTTP/1.1" 404 1021 There are no other exceptions in Tomcat logs. I have read related questions, but my test doesn't run. Spring Boot War deployed to Tomcat I have read howto-create-a-deployable-war and...

Trouble with Login using Spring Boot and JDBC Security

spring,spring-security,spring-boot
My build.gradle file: task wrapper(type: Wrapper) { gradleVersion = '2.4' } buildscript { repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE") } } apply plugin: 'java' apply plugin: 'spring-boot' repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc")...

Spring Boot- Producing a SOAP web service that expects application/soap+xml content type

web-services,soap,spring-boot,spring-ws,soap1.2
I followed a tutorial Produce SOAP WS. I changed the DefaultWsdl11Definition under WebServiceConfig to generate soap12 binding for the service by adding: wsdl11Definition.setCreateSoap12Binding(true); In my generated wsdl file, I can see that porting for Soap12 is generated. However when I send a message with custom header: Content-Type=application/soap+xml, I get exception:...

Possible to access HealthIndicator methods as endpoints?

spring,spring-boot
By implementing HealthIndicator you can add custom health checks using Spring Boot and its actuator module. These checks are listed all together using the /health endpoint. Is it possible to request these custom health endpoints, for example /health/myCustomCheck?...

spring boot switching from in-memory database to persistent database

intellij-idea,spring-boot,spring-data
I have developed my web-application using spring-boot and spring-data-jpa and and in-memory database, and I have a couple questions: how can i now switch to a persistent, let's say, MySQL database? What do I have to change in my configuration? Can spring-boot set a database up for me with a...

Issue in parsing jackson

java,json,jackson,spring-boot
I am getting json using rest templete RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); test = restTemplate.getForObject(url,Test.class, params); I am getting json like {"object":"{\"id\":123,\"userId\":159,\"contentId\":1}"} Here is my POJO @JsonIgnoreProperties(ignoreUnknown = true) public class Test { @JsonProperty("id") private String id; public String getId() { return id; } public void setId(String id)...

Spring cloud consul class not found RestTemplateCustomizer

spring,spring-boot,spring-cloud,consul
I want to use spring cloud consul for Service discovery, but getting java.lang.ClassNotFoundException: org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer , what am i missing here? my pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-commons</artifactId>...

Adding external static files (css, js, png …) in spring boot

java,spring,spring-mvc,spring-boot,thymeleaf
Background I have a spring boot application which has the logo.png file added to the static folder of the resource file, which is eventually built into the jar file which is used in the execution. This jar application need to be run in multiple instances for different clients. So what...

Timing Issue with Spring Boot Annotation Configuration

java,spring-boot,spring-annotations
We're having a curious issue with the timing of beans, repositories, and controllers in our spring boot application. We have a NodeRepository that is backed by a Map. This Map object should be a Map that we create using an @Bean annotation, but it seems as though Spring is creating...

Spring cloud: Ribbon and HTTPS

spring,spring-boot,spring-cloud
We want to use HTTPS for our microservices communication based on Feign and Ribbon. The services are based on spring boot and tomcat is correctly setup. The instances are registered with the HTTPS URL and securePort enabled on Eureka. However, when we call another microservice via Feign then the underlying...

Overwriting spring-boot autoconfiguration

java,spring,spring-boot,spring-batch
I'm a little bit confused with the behaviour of spring-boot when overwriting specific autoconfigurations. I like to partly overwrite the BatchAutoConfiguration, but I guess, my question is not specific to BatchAutoConfiguration. Actually, I just want to "overwrite" two methods of this class: public BatchDatabaseInitializer batchDatabaseInitializer() and public ExitCodeGenerator jobExecutionExitCodeGenerator(). Therefore,...

How to access spring.application.instance_id programatically?

java,spring,spring-boot,spring-cloud,netflix-eureka
I have the following content in my "applicationname.yml" file of my Spring Boot/Cloud application. How can i get the value of spring.application.instance_id in my java code ? This "applicationname.yml" file is hosted in the 'Spring Cloud Config Server'. eureka: password: password client: registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: ${vcap.services.${PREFIX:}eureka.credentials.uri:http://user:[email protected]:8761}/eureka/ instance: preferIpAddress: true...

not able to savedata to mysql db, in gradle project, Neither BindingResult nor plain target object for bean name 'goal' available as request attribute

mysql,spring-security,spring-boot,thymeleaf
I was watching tutorial and i created user-login and verifying the user, when i created addGoal, my goal was not entering in my mysql database, since i am able to login so my database connection are correct, and i am using thymeleaf with javaconfig for my annotations, please help me...

Multipart with Spring Boot Rest Service

spring,rest,spring-mvc,spring-boot
I have a REST-Service defined with as follow @RequestMapping(value = "/{userId}/profileimage/{language}", method = RequestMethod.PUT) public String uploadProfileImage(@PathVariable String userId, @RequestParam MultipartFile file, @PathVariable String language) throws IOException { ...} and defined a multipart filter @Bean public FilterRegistrationBean multipartFilter() { FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new MultipartFilter()); List<String> urlPatterns = new...

Spring Cloud Config Globals

java,spring,spring-boot,spring-cloud
I have a scenario where I need to set some properties globally for several applications. Is there support for default or global configs in spring cloud config? Example: #default.properties setting=global_setting #myapp.properties something_else=app_setting #anotherapp.properties prop=different_app_setting Here I would want for "myapp" to have setting set. Any help would be greatly appreciated....

How to get all self injected Beans of a special type?

spring,spring-boot,spring-bean
I would like to build a Spring application, where new components can be added easily and without much configuration. For example: You have different kinds of documents. These documents should be able to get exported into different fileformats. To make this functionality easy to maintain, it should (basically) work the...

how to Autowire the applicationContext early?

spring,spring-boot
Using spring boot, how to Autowire the applicationContext ? It must be autowired before the call of endpoint() @Configuration @EnableTransactionManagement @EnableAutoConfiguration @ComponentScan({"com.dev.core.services", "com.dev.core.wservices"}) @ImportResource({ "classpath:META-INF/cxf/cxf.xml" }) public class ContextConfig extends SpringBootServletInitializer { @Autowired private static ApplicationContext applicationContext; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return...

How do I limit the amount of times a JMS DefaultMessageListenerContainer will retry a message in ActiveMQ?

spring-boot,activemq
How do I limit the amount of times a JMS DefaultMessageListenerContainer will retry a message with SpringBoot and ActiveMQ.( I know we can achieve this using JMSXDeliveryCount property in IBM MQ messageListener).

Spring AuthenticationManagerBuilder Password Hashing

spring,spring-security,spring-boot
I'm trying to set up user authentication in Spring, but after adding password hashing it doesn't authenticate. I am using Spring Boot and Spring Security. Here is a shortened version of my code: Customer entity: @Entity public class Customer { private String username; private String password; public Customer() { }...

Spring boot - adding a filter

filter,spring-boot
I am wondering how I can add a filter in spring boot if the java class is only available in the app container ie it is not available at compile time. FilterRegistrationBean can only add a Filter class and not a String of a class name that will get instantiated...

spring-boot integration testing using rest-assured

maven,spring-boot,h2
I have been struggling with the issue of starting the H2 db in my tests. This is how the tests are annotated - @SpringApplicationConfiguration(classes = ServiceApplication.class) @WebAppConfiguration @IntegrationTest("server.port:8084") @PropertySource("test:application.properties") public class testSerivce{ //test scenario } The in memory db H2 is used and this is how its setup in application...

Spring boot don't let me create a repository without database

spring,spring-boot,spring-data
I've created a project on Spring Boot. I've two providers extending the same Abstract provider, and i load on startup the one i'm interested in via Spring Profile. One of the providers is based on JPA, the other have his interface implemented where i make calls to webservices. This is...

Running a specific spring batch job amongst several jobs contained withing a spring boot fat jar

java,jar,spring-boot,spring-batch
I am trying to run a spring batch job from a spring boot fat jar and I am having issues referencing the nested jars. Here is the command I use: java -cp bignibou-batch-core/build/libs/bignibou-batch-core.jar:lib/spring-batch-core-3.0.3.RELEASE.jar org.springframework.batch.core.launch.support.CommandLineJobRunner com.bignibou.batch.configuration.BatchConfiguration mailingJob Notice how I reference the nested spring batch jar using the colon. Why is...

Dynamic fields thymeleaf list iteration

spring,spring-mvc,spring-boot,thymeleaf
I'm getting a really weird error ! while iterating on list thymeleaf identified index as a property of my bean and not an index value ! <div th:each="phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field col s4" > <input th:field="*{phones[__${phoneStat.index}__].number}" th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text" class="validate" /> <label...

getting 401 to access http://localhost:8080/oauth/token

java,javascript,angularjs,oauth,spring-boot
I am hitting one end point from my angularjs client app to login when I am doing that one I am getting the following ERROR in browser console OPTIONS http://localhost:8080/oauth/token XMLHttpRequest cannot load http://localhost:8080/oauth/token. Invalid HTTP status code 401 It's server side code to accept CORS from the client. @Component...

Service not starting using Spring-boot during integration tests

tomcat,spring-boot,rest-assured
I am writting my tests useing rest-assured and spring-boot. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = ApplicationSErvice.class) @WebAppConfiguration @IntegrationTest("server.port:0")//dynamically pick up ports public class MyTestClass{ @Value("${local.server.port}") int port; @Before public void setup(){ RestAssured.port=port; } @Test public void testMethod(){ //asserting } In the log I see it says starting Tomcat on port and STarting service...

NoSuchBeanDefinitionException, but bean is defined

java,spring,spring-boot
I am attempting to get the configurations into Spring Boot using Java based config instead of XML config from this blog post: http://blog.novoj.net/2012/03/27/combining-custom-annotations-for-securing-methods-with-spring-security/ I am getting the following exception: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'postAuthorizeAdvisor' defined in class path resource [test/project/security/aop/AopSecurityConfiguration.class]: Unsatisfied dependency expressed through constructor argument with...

SyntaxError: Unexpected token Y at Object.parse (native)

angularjs,spring-boot
I am uploading a file using spring boot and angular js but when i click on import i have the erros mentioned in the title. Here's my controller js var app=angular.module("MyCat",[]); app .directive("fileread", [function () { return { scope: { fileread: "=" }, link: function (scope, element, attributes) { element.bind("change",...

Spring Boot War file gets 404 on ec2

tomcat,amazon-ec2,spring-boot,.war
I put together a simple Eclipse Spring Boot Rest program. Just a couple of endpoints that return some stings. I am building it with the Eclipse Gradle plug-in. No problems, it runs fine in the Eclipse provided Tomcat instance. I also ran it on a native windows Tomcat. I deployed...

Spring boot security with 3 fields authentication and custom login form

spring,security,spring-security,spring-boot
I'm using spring boot and i need to implement spring security with 3 fields authentication process username, password and corporate identifier as a hidden input in a form. I implemented a custom usernamepasswordauthenticationfilter but it not seems to be enough to setup the security config. EDIT : Users don't seem...

how to use Spring-EL in @Value when using constants to resolve a property

spring,spring-boot,spring-el,spring-environment
I'm trying to use a constant to define a property and then resolving it with the @Value annotation. I defined the constant in an interface: public interface InternalConstant{ public static final String JOB_NAME_PROPERTY = "javabatch.jobName"; } I'm using springboot and I'm adding the property as a default property to the...

Possible to use Spring Boot 1.3.0.M1 with Spring Cloud?

spring-boot,spring-cloud
I'd like to be able to start using Spring Boot 1.3.0.M1 (and by extension Spring 4.2.0.RC1) along with Spring Cloud (config server, eureka, ribbon, feign, and zuul). I'm using a gradle build, so initially I was using the dependencyManagement plugin like this: dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-starter-parent:1.0.3.BUILD-SNAPSHOT" } }...

AWS Instance Profile doesn't work with Spring Cloud AWS

java,amazon-web-services,spring-boot,spring-cloud
I have a small Spring Boot app, using Spring Cloud AWS (1.0.0.RELEASE) to access SQS queue. It is beeing deployed on an EC2 instance with Instance Profile set. It appears that AWS side of things is working, as I can access both relevant metadata links: iam/info and iam/security-credentials/role-name, and they...

Neo4J IndexProvider is deprecated

spring,neo4j,spring-boot,spring-data-neo4j
The project https://github.com/neo4j-contrib/developer-resources/tree/gh-pages/language-guides/java/spring-data-neo4j produces a warning: Class 'org.springframework.data.neo4j.support.index.IndexProvider' is marked deprecated I use Spring Boot. The managed version for spring-data-neo4j is 3.2.2.RELEASE Does anybody know how this deprecation can be resolved?

Spring boot, error defining bean from same interface and class

java,spring,spring-boot
I have a class that define a list of zipcodes. In my Application class I define two objects of the same class and interface but with different information from application.yml @Configuration @ComponentScan @EnableAutoConfiguration public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean @ConfigurationProperties(prefix...

How to make data repository available in spring boot unit tests?

spring-boot,spring-jpa
I'm consistently getting NPE on the repository I'm trying to implement. Here's the repo: public interface EmployeeRepository extends CrudRepository<Employee, Long> { Employee findByEmployeeId(String employeeId); } I'm just trying to do a simple integration test to make sure the app is wired correctly: public class EmployeeRepositoryTest extends BaseIntegrationTest { private static...

spring boot setContentType is not working

spring,spring-boot,content-type
I'm trying to return an image on spring-boot (1.2.2) How should I set the content-type? Non of the following are working for me (meaning that response headers are not containing 'content-type' header at all ): @RequestMapping(value = "/files2/{file_name:.+}", method = RequestMethod.GET) public ResponseEntity<InputStreamResource> getFile2(final HttpServletResponse response) throws IOException { InputStream...

Why is my spring boot stateless filter being called twice?

rest,spring-security,spring-boot,restful-authentication,jwt
I'm trying to implement stateless token-based authentication on a rest api I've developed using Spring Boot. The idea is that the client includes a JWT token with any request, and a filter extracts this from the request, and sets up the SecurityContext with a relevant Authentication object based on the...

How should I use @Cacheable on spring data repositories

java,spring-boot,spring-data
When using, for example, MongoRepository there are some methods which I would like to mark as @Cacheable such as insert(entity) or findOne(id). Since its spring repository and not mind, how should I use @Cacheable on those methods?

Spring Boot Actuator Info Endpoint Version from Gradle File

gradle,spring-boot
I'd like the /info actuator endpoint from my Spring Boot (1.2.4.RELEASE) application to return the version as specified in the build.gradle file. In my build.gradle file I have a line as so: version = '0.0.1-SNAPSHOT' I am using yaml configuration file. Right now I have the version duplicated as so...

Mock class inside REST controller with Mockito

java,testing,junit,spring-boot,mockito
I have a spring-boot application which exposes a REST interface via a controller. This is an example of my controller: @RestController public class Controller { @Autowired private Processor processor; @RequestMapping("/magic") public void handleRequest() { // process the POST request processor.process(); } } I am trying to write unit tests for...

Java task scheduler run daily from start to end date

spring-boot,scheduled-tasks
I've got a spring boot application in java with some scheduled tasks I need to run at midnight every day, from 15th June to 15th August @Scheduled(cron = "0 0 0 15-30 5 ?") // Midnight every day from 15th June until end of month public void sendReminderEmailsJune() { doStuff();...

Jsp list output [email protected]?

jsp,spring-mvc,spring-boot
I have a list of tweets inside a user and when I iterate through them all I get is the object but not the actual text <c:forEach items = "${tweets}" var="user" ></c:forEach> <h1><c:out value="${user.tweets}" /></h1> </div> how do I get the value of the tweets, they all save as text...

How to Fetch Data using Spring Data

spring,jpa,spring-boot,spring-data
Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i...

Spring Boot - return dates (not as timestamps)

java,spring,spring-boot
I'm using Spring-Boot 1.2.2 with this code: @RequestMapping(value = "/dates", method = RequestMethod.GET) public Date getDates() { return new Date(); } which returns this response: 1433241315047 How can I make it return "Sun May 31 16:26:43 IDT 2015" ? I found some examples on Google like mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false) but can't...

Redirect http to https on spring boot embedded undertow

java,spring,spring-boot,undertow
I am using spring boot (1.2.3) and embedded undertow. For security reasons I would prefer to redirect any http request to https but I cannot find an example for doing this. Here is an example for spring boot and tomcat: Spring boot - Embeded Tomcat HTTP to HTTPS redirect Does...

Extract data from excel to mysql in java

java,spring-boot
I want to extract data from excel to mysql but at the beginning i want just to read the file so i use the code below : @RestController public class ExtractDataController { protected String[] celluls; @RequestMapping(value = "/readExcel", method = RequestMethod.GET) public String processExcel() { try { InputStream ExcelFileToRead =...

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms
We are receiving a compilation error in the following code, while trying to set the targetConnectionFactory. According to the example given in Spring 4 documentation for UserCredentialsConnectionFactoryAdapter, the setTargetConnectionFactory() method takes the object of JndiObjectFactoryBean as an argument. But, looks like the JndiObjectFactoryBean hasn't implemented the 'ConnectionFactory' interface, which is...

spring boot setting up message.properties and errors.properties file in the project structure and reading file to code

spring,spring-mvc,spring-boot
I am new to spring boot. I want to add external properties files in project structure . Files are errors.properties, messages.propeties and sql.properties file which contains the all sql queries. I get it where to add it i.e \demo\src\main\resources\errors.properties file. Can Anyone of you give me insight how to read...

Elasticsearch Spring boot integration test

java,elasticsearch,spring-boot,integration-testing
I am looking for the way to add embedded elasticsearch to my spring boot integration test. I looked at elastic search integration test but it does not work together with spring boot as both should uses different test runner. I have a class test as below unfortunately it does not...

I am getting an exception: java.lang.IllegalStateException: getOutputStream() has already been called for this response

java,spring-mvc,spring-boot
I want to write code to download a file which is persisted in my system Here is my code: In a controller class I have following mapping @RequestMapping(value = "/processFile", method = RequestMethod.POST) public @ResponseBody ModelAndView downloadFileProcess( @RequestParam("file") File originalFile, @RequestParam("action") String action, HttpServletResponse response) { ModelAndView model = new...

Is it possible to deactivate MongoHealthIndicator in the Springboot spring actuator health endpoint?

spring,spring-boot
In the springboot project that I work on there is a transitive maven dependency on spring-data-mongodb. Therefore the MongoHealthIndicator seems to be activated automatically although the project does not actually use mongodb. Is it possible to deactivate specifically this HealthIndicator without deactivating the actuator health endpoint? A workaround that I...

Rest Custom HTTP Message Converter Spring Boot 1.2.3

spring,spring-boot,spring-4,spring-restcontroller,spring-json
I want to create a custom of HttpMessageConverter using Rest, Json, Spring Boot 1.2.3 and Spring 4, However my custom HTTPMessageConverter its' never called. I have preformed the following steps : 1: Created a class that extends AbstractHttpMessageConverter @Component public class ProductConverter extends AbstractHttpMessageConverter<Employee> { public ProductConverter() { super(new MediaType("application",...

How to handle exception between spring REST web services

java,rest,exception-handling,spring-boot
I have two web services based on Spring boot, REST and MVC. The first service(DesignService) project calls the second service(UserService) project passing a email as parameter and gets the user object(User.java) back. How can I handle if no user is found. DesignService project repository.java @Autowired RestTemplate restTemplate; getUser(String email){ restTemplate.postForObject("url...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa
I'm using Hibernate in a Spring Boot app. I'm making a new CrudRepository for all my Model objects, to do basic CRUD tasks. They look like this: @Repository public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> { } But then I always need to do some additional things, like custom search queries...

Spring Boot - How to kill current Spring Security session?

spring,spring-security,spring-boot
Currently I know that my setup is working because I was able to login properly using the basic HTTP authentication. I used these properties: security.basic.enabled=true security.user.name=user security.user.password=1qaz2wsx security.user.role=USER However, I want to relogin again. I tried clearing cookies (I assumed it was saved there), I checked my local/session storage and...

Spring Boot REST display id of parent only in a JSON response

json,spring,rest,spring-boot
Assume I have the following class: public class ChildEntity { ... @ManyToOne private ParentEntity parent; ... } Now, I have a REST endpoint that retrieves a child entity object from the database, thus my JSON is the following: {"id": "123", "name":"someName", "parent": { //parent fields here } ... } I...

How to run flyway:clean before migrations in a SpringBoot app?

spring-boot,flyway
I am using Springboot and Flyway. The migrations work just fine but I wanted to be able perform a clean flyway command when the application context gets loaded with test profile. Is it possible to configure SpringBoot to do clean and then migrate if active profile is test?...

Spring-boot @Value binding Issue

spring,spring-boot
Facing a weird issue with spring-boot property-resolver. Trying to do a simple @Value for one of the properties. In the debug log, i see the property being matched,, but reporting it as unable to find a few lines later. Any idea on what's going wrong? Java code: @Configuration public class...

Avoid inserting duplicates into MySQL while reading an excel file using spring boot

java,mysql,excel,spring-boot
I am using spring boot to read an Excel file. I read the name of each sheet and insert them into a database. I want to check if the name already exists, before inserting the name of the sheet. I want to only insert the name if it doesn't already...

How to fetch record on the basis of @DBRef in collection in mongodb?

mongodb,spring-boot
Hi i am using mongodb with springboot and not able to fetch records on the basis of @DBRef. My scenerio is: I have AuthenticationToken Collection and User collection as follows: { "_id" : ObjectId("556bdfc2ccf2e6509f8a2849"), "_class" : "com.samepinch.domain.user.AuthenticationToken", "token" : "2efd1cfe-2f2f-4163-b500-bac6e4654287", "createdDate" : ISODate("2015-06-01T04:29:54.364Z"), "updatedDate" : ISODate("2015-06-01T04:29:54.364Z"), "user" : DBRef("users", ObjectId("556bdfc2ccf2e6509f8a2848"))...

Spring Integration Test Loading Annotated Beans

java,spring-boot,integration-testing,junit4
For some reason, my DAO is not loaded when I use @ComponentScan alone. My DAO: @Repository public class MyDAO{ @Autowire private Datasource ds; } My Config class (just overrides datasource bean with an embedded DB): @Configuration public class TestConfig extends AppConfig { @Bean public Datasource getDatasource() throws Exception{...} My Test...

Spring AOP not working, when the method is called internally within a bean

java,spring,spring-boot,spring-aop
I have several Aspects coded in my application. All others works except for the following. Service Interface package com.enbiso.proj.estudo.system.service; ... public interface MessageService { ... Message reply(Message message); Message send(Message message); ... } Service Implementation package com.enbiso.proj.estudo.system.service.impl; .... @Service("messageService") public class MessageServiceImpl implements MessageService { ... @Override public Message reply(Message...

Spring boot using Spring Security authentication failure when using SpringPlainTextPasswordValidationCallbackHandler in an XwsSecurityInterceptor

spring-security,spring-boot,spring-ws,ws-security
I have set a up a spring boot (1.2.3) application with spring security and spring-ws. I have configured spring security to use .ldapAuthentication() for authentication in my WebSecurityConfigurerAdapter. I am trying to get the same spring security authenticationManager to authenticate my spring ws SOAP web services using ws-security usernametokens (plain...

Spring Boot not displaying web contents

spring,spring-mvc,spring-security,spring-boot
I have a Spring Boot Application used as a secured REST API backend. I would like to have some static page with the documentation about that API (I'd like to use a Wiki, for instance) As far as I try I cannot make it display static contents: e.g. I tried...

disable RabbitAutoConfiguration programmatically

spring,spring-boot
Is there a programmatic(properties based) way of disabling RabbitAutoConfiguration in spring boot (1.2.2). Looks like spring.rabbitmq.dynamic=false disables just the AmqpAdmin but not the connection factory etc. We want a model where app properties might be sourced from spring cloud config (includes control bus) or via -D jvm args. This decision...

How to access entity manager with spring boot and spring data

spring-boot,spring-data,spring-data-jpa
How to get access to the entity manager in the repository when we use spring boot and spring data? Otherwise, i will need to put my big query in annotation, i would prefer to have something clear... then a long text....

Spring Boot SSL Client

spring,rest,ssl,spring-boot,ssl-certificate
I am new to Spring Boot. So far I am enjoying it. I have developed a demo SSL rest web server that correctly handles mutual X.509 certificate authentication. Using an IE browser with self signed client & server certificates, I have tested that the demo rest web server is working...

ehCache Statistics with spring boot

statistics,spring-boot,ehcache
I have spring boot application with ehcache as below @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); //ehCacheManagerFactoryBean.setCacheManagerName("messageCache"); ehCacheManagerFactoryBean.setShared(true); return ehCacheManagerFactoryBean; } @Bean public EhCacheCacheManager cacheManager() { return new...

@RestController not found, if main class not in top level package

java,spring,spring-boot
I have a class Resource annotated with @RestController, but it is only used if the main class App annotated with @SpringBootApplication is in the top level package. Works: com +- test +- project +- App.java | +- resources | +- Resource.java Does not work: com +- test +- project +-...

Spring framework unable to start embedded container

java,spring,maven,spring-mvc,spring-boot
I'm following Spring in Action 4th Edition Chapter 5, but I'm stuck at the very first example. Here is my Eclipse Luna project structure: If I run this project as Spring Boot App, then it throws exceptions: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start...

Spring Boot MVC non-role based security

java,security,spring-mvc,spring-boot
I am attempting to setup security in a new Spring Boot MVC application. I am attempting to do this with no XML configuration, only Java. Currently I have been able to get role based security working using the @Secured annotation on each of my @RequestMapping methods. I also need to...

Get Spring Bean from AspectJ ProceedingJoinPoint

spring,spring-boot,spring-data,aspectj
I'm looking to get the Spring Data Repository interface or the bean calling void delete(id) using AspectJ, the problem with that function is there is no argument or return type to guess the bean, is there any idea how to get the calling bean or the interface name from AspectJ...

The method and() is undefined for the type HttpSecurity

angularjs,spring-boot
Im trying to follow this example that is basically a bit of code to actually invalidate de login on angular.js. I get "The method and() is undefined for the type HttpSecurity" This is my part of my Code (line 89): @EnableWebMvcSecurity @Configuration @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {...

DefaultRebelLaunchConfigProvider - unknown type org.springframework.ide.eclipse.boot.launch

java,spring,spring-boot,jrebel
I am setting up a basic Spring Boot application (1.2.3.RELEASE) on Spring Tool Suite 3.6.4.RELEASE. I decided to install jRebel using myJRebel (6.2.0). When I start my application (Run as Spring Boot App), I can't see the jRebel logs in the console. I already checked my project under jRebel config...