Menu
  • HOME
  • TAGS

Spring Boot OAuth2 Custom Login Form Use case

spring-boot,spring-security-oauth2

<input type="hidden" name="scope.openid" value="true"/> <input type="hidden" name="scope.openid" value="false"/> The client scope is not set in the authorize form. Add extra inputs to the form for approve and deny requests as shown above....

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

java,spring,spring-boot,jrebel

If your project is using embedded container, it should have main method. I would try to run it as Java application. According to Spring Boot docs, JRebel should work....

Spring AuthenticationManagerBuilder Password Hashing

spring,spring-security,spring-boot

Do not encode the password in the set method of your Entity. you only need to do this on creat new user . Spring security will deal with the rest

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

java,logging,spring-security,spring-boot,dependency-management

i figured out compile("org.springframework.boot:spring-boot-starter-security"){ exclude module: "spring-boot-starter-logging" exclude module: "logback-classic" } compile("org.springframework.boot:spring-boot-starter-thymeleaf"){ exclude module: "logback-classic" } ...

Spring Boot not displaying web contents

spring,spring-mvc,spring-security,spring-boot

According to the Spring Guide: Building a RESTful Web Service A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data...

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

java,mysql,excel,spring-boot

Why not use the exists() method instead of what you are doing? That is what it is there for. boolean exists(ID id) Returns whether an entity with the given id exists. if(!te.exits(wb.getSheetName(i))){ TableEntity t=new TableEntity(wb.getSheetName(i), ""); te.save(t) } ...

spring boot switching from in-memory database to persistent database

intellij-idea,spring-boot,spring-data

You can change the application properties for the datasource according to the link Gabor Bakos already provided. That depends on the type of the database you want to use. HSQLDB and H2 allow you to specify a file path for the database file, however the database instance itself is...

disable RabbitAutoConfiguration programmatically

spring,spring-boot

First you need to exclude RabbitAutonfiguration from your app @EnableAutoConfiguration(exclude=RabbitAutoConfiguration.class) Then you can import it based on some property like this @Configuration @ConditionalOnProperty(name="myproperty",havingValue="valuetocheck",matchIfMissing=false) @Import(RabbitAutoConfiguration.class) class RabbitOnConditionalConfiguration{ } ...

How should I use @Cacheable on spring data repositories

java,spring-boot,spring-data

Not sure how you're actually using MongoRepository, you seem to suggest you're using it directly (it's often a good idea to include your code in the question), but the reference documentation explains the basics of working with this interface (and all repository interfaces in Spring Data, as a matter of...

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms

The big difference between your code and the example is in the XML config example that myTargetConnectionFactory is actually a bean managed by Spring. You aren't doing that. You are just creating a new object Spring doesn't know about. The magic happens when setting the targetConnectionFactory of myConnectionFactory. Even though...

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

java,spring,spring-boot,postconstruct

@PostConstruct can be used to make sure application has the stuff that you need when it starts like DB pooling etc. For example, you can throw IllegalStateException() if the file is not there and it can stop the application from loading. I ran a quick test and it works. You...

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

spring,spring-boot,spring-el,spring-environment

What about the simplest approach: @Value("${" + InternalConstant.JOB_NAME_PROPERTY + "}") private String jobName ...

Spring Integration Test Loading Annotated Beans

java,spring-boot,integration-testing,junit4

The following setup will load default beans from AppConfig, while overriding any beans specified in TestConfig. TestConfig can be a nested class (within MyDAOTest) as long as it is declared static. @ContextConfiguration( classes = TestConfig.class ) @RunWith(SpringJUnit4ClassRunner.class) public class MyDAOTest { ... } @Import(AppConfig.class) public class TestConfig { @Bean public...

How to access spring.application.instance_id programatically?

java,spring,spring-boot,spring-cloud,netflix-eureka

You miss metadata block. Use: @Value("${eureka.instance.metadataMap.instanceId}") String instanceId; As far as I know there is no instance_id property in spring.application namespace....

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

spring,spring-boot,spring-bean

You can get all instances of a given type of bean in a Map effortlessly, since it's a built in Spring feature. Simply autowire your map, and all those beans will be injected, using as a key the ID of the bean. @Autowired Map<String,Exporter> exportersMap; If you need something more...

Issue in parsing jackson

java,json,jackson,spring-boot

I am able to solve it.Here is my solution @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(creatorVisibility = JsonAutoDetect.Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class Test { @JsonProperty("id") private String id; @JsonProperty("userId") private int userId; @JsonProperty("contentId") private int contentId; public Test() { } @JsonCreator public static Test getJson(String json) throws IOException { ObjectMapper mapper = new ObjectMapper();...

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

spring-boot,flyway

You can overwrite the Flyway autoconfiguration like this: @Bean @Profile("test") public Flyway flyway(DataSource theDataSource) { Flyway flyway = new Flyway(); flyway.setDataSource(theDataSource); flyway.setLocations("classpath:db/migration"); flyway.clean(); flyway.migrate(); return flyway; } In Spring Boot 1.3 (current version is 1.3.0.M1, GA release is planned for September), you can use a FlywayMigrationStrategy bean to define the...

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

spring-boot,activemq

The easiest approach is to use the RedeliveryPolicy available in for ActiveMQ. To use it with spring boot, you could enable it as query params on the Broker URL. tcp://localhost:61616?jms.redeliveryPolicy.maximumRedeliveries=5 You can tweak other features, such as time between redelivery etc with the options described in activemq.apache.org/redelivery-policy.html....

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

Lets take a step back focus on restless state first. For your form use this: <form th:object="${goal}" th:action="@{/addGoal}" method="post"> <div> <label> Enter Minutes : <input type="text" th:field="*{minutes}" /> </label> </div> <div> <input type="submit" value="Submit" /> </div> </form> Next change: @RequestMapping(value = "addGoal", method = RequestMethod.GET) public String addGoal(Model model, HttpSession...

Service not starting using Spring-boot during integration tests

tomcat,spring-boot,rest-assured

For web integration testing, you should use @WebIntegrationTest instead. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest public class ApplicationTest { @Value("${local.server.port}") private int port; @Before public void setup() { RestAssured.baseURI = "http://localhost:" + port; } @Test public void testStatus() { given().contentType(ContentType.JSON).get("/greeting").prettyPeek().then().statusCode(200); } @Test public void testMessage() {...

Not Able to Resolve View Using Spring boot

spring,spring-mvc,spring-boot

Here could be two issues one them are dependencies. 1.These three dependencies could help you: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId>...

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

angularjs,spring-boot

Unexpected token 'Y' - is starting of your message from java controller 'You successfully ...' that comes from the server instead of valid JSON string. Try to return something parseable: {"result": "You successfully bla-bla-bla..."}

Spring boot - adding a filter

filter,spring-boot

If your Filter has a no-args constructor this should work. try { Class c = Class.forName("com.runtimeFilter"); Filter filter = (Filter)c.newInstance(); //register filter with bean } catch (Exception e) {} If it has a constructor with args you need to use the getConstructor() method on Class....

Timing Issue with Spring Boot Annotation Configuration

java,spring-boot,spring-annotations

I don't think it is timing issue. You are "in conflict" with this spring feature (from http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/) Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding...

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

spring-boot,spring-cloud

There is an open issue to support Spring Boot 1.3.0.

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

java,jar,spring-boot,spring-batch

I turns out that there is a nice option to choose one job (out of multiple jobs) from within a fat jar: --spring.batch.job.names=jobOne,jobThree Only jobOne & jobThree will run even if jobTwo also exists. See http://docs.spring.io/spring-boot/docs/current/reference/html/howto-batch-applications.html for documentation. So as far as I am concerned, this sorted my problem: java...

How to Fetch Data using Spring Data

spring,jpa,spring-boot,spring-data

You want to find all books for a specific author so, given an Author, retrieve all Books whose set of Authors contains the specified Author. The relevant JPQL operator is: http://www.objectdb.com/java/jpa/query/jpql/collection#NOT_MEMBER_OF_ [NOT] MEMBER [OF] The [NOT] MEMBER OF operator checks if a specified element is contained in a specified persistent...

Spring-boot+JPA EntityManager inject fails

spring,java-ee,jpa,spring-boot,cdi

You should use the dependency for spring-boot-starter-data-jpa <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> And to use a persistence xml you should define a bean as it says in the documentation. Spring doesn’t require the use of XML to configure the JPA provider, and Spring Boot assumes you want to take advantage of...

Spring Boot MVC non-role based security

java,security,spring-mvc,spring-boot

Maybe @PreAuthorize or @PostAuthorize will be enough for you, it depends what exactly u need. You can try sth like this: @PostAuthorize("returnObject.widget.owner.id == principal.id") public Widget getWidgetById(long id) { // ... return widget; } UPDATE: You can use Pre/Post Authroize since Spring Security 3.0 and as you said it provides...

Cucumber Test a Spring Boot Application

java,spring,spring-boot,cucumber-jvm

I have solved the issue with some help from this question. Here is the repository with the answer: https://github.com/jakehschwartz/spring-boot-cucumber-example In short, the AbstractSpringTest class needs to have the following annotations: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = DemoApplication.class, loader = SpringApplicationContextLoader.class) @WebAppConfiguration @IntegrationTest ...

spring-boot without template engine

spring-mvc,spring-boot

If you want to use static resources like HTML and JavaScript you can place them into a subfolder of /src/main/resources named /public, /static or /resources. For example a file located at /src/main/resources/public/dummy/index.html will a accessible via http://localhost/dummy/index.html. You won't need a Controller for this. See also the Reference Guide....

spring-boot integration testing using rest-assured

maven,spring-boot,h2

Are you using Eclipse? I somehow noticed that src/main/resources/application.properties gets excluded from the Java Build Path, if you generate the project with the "eclipse:eclipse" maven goal. To workaround this you can either add a src/test/resources/application.properties or correct the Java Build Path. I don't know if this behavior is intended. I...

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

spring-boot

It doesn't matter, which one you choose, as long as it is packaged in the actuator JAR (which is the case for both of the classes you mentioned).

How to handle exception between spring REST web services

java,rest,exception-handling,spring-boot

Return null, or if you're on Java 8, an empty Optional If no user is found, return an empty Response with a 404 (NOT_FOUND) status, i.e. new ResponseEntity(HttpStatus.NOT_FOUND); Catch org.springframework.web.client.HttpClientErrorException Finally, why are you POSTing to an endpoint that only returns a resource? You should be doing a GET,...

Deserialize jackson in spring boot

java,json,jackson,spring-boot

You can modify CustomJacksonDeserialize like this : class CustomJacksonDeserialize extends JsonDeserializer<Activity> { @Override public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, NullPointerException { JsonNode jsonNode = jsonParser.readValueAsTree(); String name=jsonNode.get("results").get(0).get("testing").get("name").asText(); return new Activity(name); } } Second Approach: Alternatively If you can also de-serilaize this JSON using Object mapper itself This does...

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

spring,spring-boot

From: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html # HEALTH INDICATORS (previously health.*) ... management.health.mongo.enabled=true ... You should be able to set that to false to disable the health indicator. From org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration.java @Configuration @ConditionalOnBean(MongoTemplate.class) @ConditionalOnProperty(prefix = "management.health.mongo", name = "enabled", matchIfMissing = true) public static class...

how to Autowire the applicationContext early?

spring,spring-boot

static fields are ignored by Spring. Unless you're in some kind of main method, setting up your application, you should never have to use the ApplicationContext directly. Here, you want to use it to extract a bean of type IWCustomerService. Instead, let Spring inject it for you. @Bean public EndpointImpl...

Spring Boot Actuator Health Returning DOWN

spring-boot

In your Spring properties, set endpoints.health.sensitive = false. The /health endpoint will then return the list of various health indicators and you can debug from there. For a production environment you should enable security around the /health endpoint....

Why is my spring boot stateless filter being called twice?

rest,spring-security,spring-boot,restful-authentication,jwt

Okay - so this is pretty ridiculous, but it seems like it's an issue with the way I was invoking the request (via the POSTMAN Chrome Extension) Postman seems to fire in 2 requests, one with headers, one without. There's an open bug report describing this here : https://github.com/a85/POSTMan-Chrome-Extension/issues/615 The...

Spring Cloud Config Globals

java,spring,spring-boot,spring-cloud

According to the documentation properties in application.yml or application.properties are available to every application.

Spring framework unable to start embedded container

java,spring,maven,spring-mvc,spring-boot

When using Spring Boot you should not include the other Spring dependencies directly, but rely on Boot's own dependency management. When using the provided "starters" you can be sure that all needed libraries will be included in a matching version. Instead of including spring-mvc artifact in your pom.xml: <dependency> <groupId>org.springframework</groupId>...

NoSuchBeanDefinitionException, but bean is defined

java,spring,spring-boot

I have found out how to correct this, not entirely sure why this works, but it does. I removed the AopSecurityConfiguration class and moved the methodSecurityInterceptor method to my WebSecurityConfigurerAdapter implementation and removed the authenticationManager argument. In the method I am now calling the authenticationManager method of the WebSecurityConfigurerAdapter. Doing...

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

spring,spring-boot,spring-data

It was a human error in fact. I'v forgotten a spring.datasource.platform = hsqldb in my application.properties file. I wasn't looking at it cause i'm using spring profiles so i was looking at my application-massilia.properties wich contains spring.datasource.platform = none and is listened now cause i've deleted the duplicate in the...

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

java,spring,spring-boot,spring-aop

Thank you jst for clearing the things up. Just for the information purposes for the future developer in SO, I'm posting the full answer to this question Lets assume that there is a bean from SimplePojo public class SimplePojo implements Pojo { public void foo() { this.bar(); } public void...

How to handle form submission in HTML5 + Thymeleaf

html5,forms,spring-boot,thymeleaf

I believe there could be 2 parts to your question and I will try to answer both. First on the form itself how would you get to a child_id to display fields from another object on the form. Since your Person class does not have a Child relationship you would...

Spring Boot - How to kill current Spring Security session?

spring,spring-security,spring-boot

If you use basic authentication, the browser stores the authentication until you close it (or exit the incognito mode, if you used it). There is no possibility to delete the session on server side, since the browser would just reauthenticate. If you want to be able to logout, use form...

Dynamic fields thymeleaf list iteration

spring,spring-mvc,spring-boot,thymeleaf

Actually when binding fields to a form, in order to acces to a list with th:each. As the doc specify, we should use the two variable item, and phoneStat this way and not just phoneStat : <div th:each="item, phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field...

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

web-services,soap,spring-boot,spring-ws,soap1.2

You need to configure Spring WS to use SOAP 1.2, as explained here: Producing SOAP webservices with spring-ws with Soap v1.2 instead of the default v1.1...

Extract data from excel to mysql in java

java,spring-boot

I assume it's the usage of < sheet.getLastRowNum() for your first for loop: getLastRowNum() --> last row contained n this sheet (0-based) (see https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFSheet.html#getLastRowNum()) Hence this is NOT the number of rows, but the index of the last row! So, if you have 2 rows, this will return 1, since...

spring boot setContentType is not working

spring,spring-boot,content-type

Got it... Had to add ByteArrayHttpMessageConverter to WebConfiguration class: @Configuration @EnableWebMvc @ComponentScan public class WebConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) { httpMessageConverters.add(new ByteArrayHttpMessageConverter()); } } And the then my second attempt (getFile3()) was working correctly...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa

There are lots of ways you could probably accomplish this. If you really need absolute control try this interface FoobarRepositoryCustom{ List<Foobar> findFoobarsByDate(Date date); } interface FoobarRepository extends CrudRepository<Foobar, Long>, FoobarRepositoryCustom public FoobarRespoitoryImpl implements FoobarRepositoryCustom{ @PersistenceContext private EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar...

ehCache Statistics with spring boot

statistics,spring-boot,ehcache

If you can afford to use a snapshot release of spring boot this feature is being added to 1.3.0. Right now you won't get that in 1.2.X

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

java,spring,spring-boot

I assume you are using a @SpringBootApplication annotation. You should know it is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan. From the documentation ComponentScan configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's element. One of basePackageClasses(), basePackages() or its alias value() may be...

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

java,javascript,angularjs,oauth,spring-boot

In case of OPTIONS request, you should not do further processing, i.e. skip the call to chain.doFilter(req, res), e.g.: HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; response.addHeader("Access-Control-Allow-Origin", "*"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers",...

Spring boot security with 3 fields authentication and custom login form

spring,security,spring-security,spring-boot

Actually i manage to find a solution to my issue. I added successHandler on successfulAuthentication was missing ! And a failureHandler too on unsuccessfulAuthentication methods. Here is my new Authentication filter : public class TwoFactorAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private static final String LOGIN_SUCCESS_URL = "{0}/bleamcards/{1}/home"; private static final String LOGIN_ERROR_URL...

Elasticsearch Spring boot integration test

java,elasticsearch,spring-boot,integration-testing

You can actually do what you need without any additional elasticsearch testing dependencies. The idea is basically to create an embedded node and then use the NodeClient to communicate with it. For that, I created my own EmbeddedElasticsearchServer class which looks (more or less) like this: public class EmbeddedElasticsearchServer implements...

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

java,spring,spring-mvc,spring-boot,thymeleaf

You can use resource handlers to serve external files - e.g. @Component class WebConfigurer extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/ext/**").addResourceLocations("file:///yourPath/static/"); } } ...

How to access entity manager with spring boot and spring data

spring-boot,spring-data,spring-data-jpa

You would define a CustomRepository to handle such scenarios. Consider you have CustomerRepository which extends the default spring data JPA interface JPARepository<Customer,Long> Create a new interface CustomCustomerRepository with a custom method signatures. public interface CustomCustomerRepository { public void customMethod(); } Extend CustomerRepository interface using CustomCustomerRepository public interface CustomerRepository extends JpaRepository<Customer,...

Spring boot war file deploy on Tomcat

tomcat,deployment,spring-boot,war

Just tried this here, and could reproduce the exact same behaviour. As silly as it sounds, most likely you are running your external tomcat under a Java 1.7 JRE (speculation), while having compiled your code against 1.8 (we know this from your pom). Strangely, there is no error, and the...

Spring Shell - usage and execution

java,spring,spring-boot,command-line-interface,spring-shell

That comment in the documentation is a bit misleading (I'll change it). For your components to be picked up, they need to be on the classpath AND you'll need to scan for them somehow. See for example how in the Spring XD project, there is a scan for the org.springframework.xd.shell...

set an annotation attribute from an environment variable?

spring,groovy,spring-boot

You can not use GStrings in java annotations in groovy. You have to use "proper" Strings. E.g. @Scheduled(cron = '${DB_CRON}') Note the single quotes here. If groovy sees a $ in "-quoted string, it will turn it into a GString. This can not be done with java annotations and you...

Getting a lost Sentinel error message for Redis

redis,spring-boot,spring-data-redis

We discovered the issue. There was a blank between the node pairs in the application.yml and once we removed this " " the Lost Sentinel log message disappeared. so from nodes: 10.202.56.209:26379, 10.202.56.213:26379, 10.202.58.80:26379 to nodes: 10.202.56.209:26379,10.202.56.213:26379,10.202.58.80:26379 It would probably be a good thing is the committers looked at this...

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

log4j,spring-boot

By default Spring boot uses Logback logging. You can change the configuration by putting a logback.xml file in your class path. They have a default base.xml which defines the overall configuration and includes their defaults.xml file. Because of where the log pattern is defined you will need to created a...

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

json,spring,rest,spring-boot

Basically returning entities directly from endpoints isn't a good idea. You make very tight coupling between DB model and responses. Instead, implement a POJO class that will be equivalent of the HTTP response you sent. This POJO will have all ChildEntity fields and parentId only and will be constructed in...

Neo4J IndexProvider is deprecated

spring,neo4j,spring-boot,spring-data-neo4j

Yes that is intentional, as the "manual" index APIs are scheduled to go away in Neo4j 3.0 this is a hint that using the manual indexes will need to change then.

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?

java,spring,spring-mvc,spring-boot

You can use an EndpointHandlerMappingCustomizer to configure the interceptors of the Actuator's endpoints. For example: @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(new Object[] { application.executeTimeInterceptor() }); } }; } ...

Spring boot, error defining bean from same interface and class

java,spring,spring-boot

You have defined 2 beans of same type. Spring boot will simply override second bean over the first. And the way you are referencing the beans is by name. So I guess what you need to do is @Qualifier at the bean definition too with the same alias as city1...

Spring-boot @Value binding Issue

spring,spring-boot

I am guessing you deployed your app as war inside a web container but you need to confirm. You need to add the method below to your class. Look at a related posting @Bean public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } ...

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

java,spring-mvc,tomcat,spring-boot

meskobalazs answered your question about the resources when building a war deployment (but notice that src/main/webapp is not read as a resource folder in a jar deployment, you have to add it as a resource in this case). When you want to change your Spring-Boot app to a web deployment...

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

spring-security,spring-boot,spring-ws,ws-security

Ok I figured this out so though I would post for anyone trying this in the future. I resolved this problem by changing my spring boot class to: @SpringBootApplication @EnableGlobalMethodSecurity(securedEnabled = true) public class SwitchxApplication extends WebMvcConfigurerAdapter { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(SwitchxApplication.class); @Bean public ApplicationSecurity applicationSecurity()...

spring boot rabbitmq MappingJackson2MessageConverter custom object conversion

java,json,rabbitmq,spring-boot,spring-amqp

Ok, I finally got this working. Spring uses a PayloadArgumentResolver to extract, convert and set the converted message to the method parameter annotated with @RabbitListener. Somehow we need to set the mappingJackson2MessageConverter into this object. So, in the CONSUMER app, we need to implement RabbitListenerConfigurer. By overriding configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) we...

Spring: @NestedConfigurationProperty List in @ConfigurationProperties

spring,properties,configuration,spring-boot

You need to add setters and getters to ServerConfiguration You don't need to annotate class with nested properties with @ConfigurationProperties There is a mismatch in names between ServerConfiguration.description and property my.servers[X].server.name=test ...

Springboot REST application should accept and produce both XML and JSON

java,xml,rest,jackson,spring-boot

Try to add a @XmlRootElement(name="myRootTag") JAXB annotation with the tag you use as the root tag to the class MatchRequest. I have had similar issues when using both XML and JSON as transport format in a REST request, but using moxy instead of Jackson. In any case, proper JAXB annotations...

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

java,spring,junit,spring-boot

Exception comes from this line: ReflectionTestUtils.setField(userResource, "userRepository", userRepository); Second parameter of setField method is a field name. UserResource has field "repository" - not "userRepository" as you try to set in your test....

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

spring,spring-mvc,spring-boot

The easiest way would be to leverage what Spring Boot already give you automatically. Anything you put into application.properties (under \demo\src\main\resources) is going to be added to your Environment. I would just take the keys from those three files and create unique entries in application.properites errors.key1=value1 errors.key2=value2 sql.key1=value1 .... Then...

Spring Boot Actuator Info Endpoint Version from Gradle File

gradle,spring-boot

This exact use case is spelled out in the Boot docs: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info-automatic-expansion-gradle So in your build.gradle do this version = '0.0.1-SNAPSHOT' processResources { expand(project.properties) } Your application.yml info: build: version: ${version} Make sure to escape any spring placeholders so it doesn't conflict with Gradle. Both use ${} as the replacement...

Redirect http to https on spring boot embedded undertow

java,spring,spring-boot,undertow

you could add Spring-Security to your project and then configure Spring-Security to enforce https. You could find a small example in the JavaDoc of org.springframework.security.config.annotation.web.builders.HttpSecurity#requiresChannel() ...

Spring cloud: Ribbon and HTTPS

spring,spring-boot,spring-cloud

We solved the zuul proxy problem now by setting ribbon.IsSecure=true eureka.instance.secureVirtualHostName=${spring.application.name} so that all services are also in the secure virtual hosts pool in com.netflix.discovery.shared.Applications. That helps the discovery process to find the instances in eureka. However, the Hystrix dashboard has still a similar problem ...

Mock class inside REST controller with Mockito

java,testing,junit,spring-boot,mockito

Shouldn't you be passing an instance to set the field on, rather than the class, e.g.: ... @Autowired private Controller controller; ... @Before public void setUp() throws Exception { ... Processor processor = Mockito.mock(Processor.class); ReflectionTestUtils.setField(controller, "processor", processor); } ...

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

java,spring,spring-mvc,spring-security,spring-boot

You can configure your TestApplication to include just the beans that you would like to test. In other words, make sure that your WebSecurityConfig is not part of the test configuration. If you read the javadoc of @SpringBootApplication you will notice that it is a composite annotation that consists of...

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

spring-boot,spring-jpa

Remove the keyword static from your repo field. Static fields aren't autowired.

Multipart with Spring Boot Rest Service

spring,rest,spring-mvc,spring-boot

You are making it way to complex, to enable file uploading simply configure it correctly using properties in the application.properties. multipart.enabled=true And make sure you have spring-webmvc on your class path (judging from the annotations used you already have). However there is one other thing and that is that file...

Rest Custom HTTP Message Converter Spring Boot 1.2.3

spring,spring-boot,spring-4,spring-restcontroller,spring-json

I believe you want to configure these message converters using the configureMessageConverters method in a configuration class that extends WebMvcConfigurerAdapter. I've done this myself with a converter for CSV content. I've included that code below. This link shows an example as well. This link may also be helpful. It seems...

Spring cloud consul class not found RestTemplateCustomizer

spring,spring-boot,spring-cloud,consul

Got this to work by upgrading the spring-cloud-commons from 1.0.0 to 1.0.1 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-commons</artifactId> <version>1.0.1.RELEASE</version> </dependency> ...

Spring Boot SSL Client

spring,rest,ssl,spring-boot,ssl-certificate

I could not get the above client submitted by Andy to work. I kept getting errors saying that "localhost != clientname". Anyways, I got this to work correctly. import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.GetMethod; public class SSLClient { static { System.setProperty("javax.net.ssl.trustStore","c:/apachekeys/client1.jks");...

Spring Boot War file gets 404 on ec2

tomcat,amazon-ec2,spring-boot,.war

I've answered a similar question here. You are running your external tomcat under a Java 1.7 JRE, while having compiled your code against 1.8. Strangely, there is no error, and the app appears in the manager app, but then you get a 404 when you're trying to access it. One...

The method and() is undefined for the type HttpSecurity

angularjs,spring-boot

addFilterAfter() already returns an instance of HttpSecurity so you can just call sessionManagement() on it without calling and() first.

Possible to access HealthIndicator methods as endpoints?

spring,spring-boot

The short answer is no. That is not provided by the actuator. You can verify this by calling the /mappings endpoint and seeing that only /health is mapped. Now the long answer is you could add your own endpoint that invokes your custom health indicator. This isn't too hard to...

Jsp list output [email protected]?

jsp,spring-mvc,spring-boot

There are two things I see wrong. First if your code is really as posted and not a typo, than you should note that you don't print anything inside a loop as you just iterate and never do anything with the user variable The following <c:forEach items = "${tweets}" var="user"...

Spring Data Rest executes query but returns 500 internal Server Error

java,spring,rest,spring-boot,spring-data-rest

Hum... This is strange but I found this question and added a controller to call the method and it worked like a charm... Obv this is not a fix, but it is a good workaround... EDIT: The error happens because it is expecting an entity, so all I had to...

Trouble with Login using Spring Boot and JDBC Security

spring,spring-security,spring-boot

There are 2 things flawed in your setup. You should post to /login instead of /j_spring_security_check as that is the new URL when using java config (and in Spring 4 for XML config also). You have set the usernameParameter to name and your form still has username. Fix those flaws...

Spring Boot and @ConfigurationProperties

java,spring,spring-boot

There is a small problem with the property entries, it should be the following: my.items[0].prop1=a my.items[0].prop2=b my.items[1].prop1=a my.items[1].prop2=b Note the items vs item, to match the setter name...