How can I do the same as: <jpa:auditing auditor-aware-ref="yourAuditorAwarebean" /> programmatically in a #Configuration class?
Is the spring xml configuration mandatory to do this?
reference: http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html#d0e2427
Java Config for auditing is now supported since Spring Data JPA 1.5 (link to documentation)
Replace the <jpa:auditing auditor-aware-ref="yourAuditorAwarebean" /> with the #EnableJpaAuditing annotation on any of your configuration class.
E.g:
#Configuration
#EnableJpaAuditing
class Config {
#Bean
public AuditorAware<AuditableUser> yourAuditorAwarebean() {
return new YourAuditorAwareImpl();
}
}
Related
i'm trying to access the values of properties file in spring framework. now i have bean file and controller. so how to access properties file value in json formate using bean
For accessing single value can be used Spring annotations "PropertySource" and "Value".
#PropertySource("classpath:application.properties")
public class SomeClass {
#Value("${some.property}")
private String someProperty;
...
}
For accessing/looping all spring properties, check this solution looping-through-all-the-properties-in-a-file-with-spring-and-java
Controller sample code:
#RestController
public class PropertiesController {
#Autowired
Properties props;
#RequestMapping(value = {"/properties"}, method = RequestMethod.GET, produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
public Set<Map.Entry<Object, Object>> getProperties() {
return props.entrySet();
}
}
if you are Using spring-boot then add spring-actuator dependency which by defaults expose /env endpoint and spits out all the properties loaded in the spring container in json format.
I have tried doing some poc on springfox swagger with spring boot. It does generate swagger ui on the same host and port as my application is running.
http://localhost:8080/swagger-ui.html
My application is composed of multiple microservices deployed on a cloud infrastructure. This way i may end up having multiple swagger hub ui as
http://microservice1:8080/swagger-ui.html
http://microservice2:8081/swagger-ui.html
http://microservice3:8082/swagger-ui.html
How i can host all of my springfox swagger hub application on same host. So that i can have a consolidate webpage to have all my api documentation at single place.
For spring rest doc, i could generate a single html document using asciidoctor for my microservice. Again i had different html docs for different microservices.
Is this feature available with spring rest doc? or in spring cloud where consolidate all my documents in one single web application.
Create a Zuul filter concept. Create a Zuul filter service and add swagger2 dependency in your pom.xml and create a configuration class in this service as mentioned below
#EnableSwagger2
#Configuration
#Component
#Primary
public class SwaggerConfig implements SwaggerResourcesProvider {
#Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
resources.add(swaggerResource("microservice1", "/microservice1/v2/api-docs", "2.0"));
resources.add(swaggerResource("microservice2", "/microservice2/v2/api-docs", "2.0"));
resources.add(swaggerResource("microservice3", "/microservice3/v2/api-docs", "2.0"));
return resources;
}
private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
Add below mentioned configuration in the other three microservices(microservice1,microservice2,microservice3..)
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.stackoverflow.login.controller"))
.paths(PathSelectors.regex("/.*")).build().apiInfo(apiEndPointsInfo());
}
private ApiInfo apiEndPointsInfo() {
return new ApiInfoBuilder().title("Spring Boot REST API").description("Employee Management REST API")
.contact(new Contact("stackoverflow", "www.stackoverflow.com", ""))
.license("Apache 2.0").licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html").version("1.0.0")
.build();
}
}
I've written a custom deserializer for an entity in Spring Boot application. Now I need to access URL parameters and path variables in my custom deserializer for some data manipulation. Please tell me how can i do that.
Thanks
For path variables deserialization you don't need to involve jackson but you have to "tune" Spring MVC itself by means of defining your own org.springframework.core.convert.converter.Converter
For example:
#Component
public class StringToLocalDateTimeConverter
implements Converter<String, LocalDateTime> {
#Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(
source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
#GetMapping("/findbydate/{date}")
public GenericEntity findByDate(#PathVariable("date") LocalDateTime date) {
return ...;
}
Here is an article about it.
1. HandlerMethodArgumentResolver
See spring-mvc-custom-data-binder, Another answer
2. HandlerInterceptor
See Interception
I want to use spring data jpa repository. And I have to connect to 2 databases. I already found so many similar questions. But most of answers are using Entity manager instead of repository.
For example
#persistenceContext(unitname = "example")
Entitymanager em;
But I want to use repository of spring data jpa. How can I configure in applicationContext.xml?
My 2 databases are MySQL and one is local another is remote server.
You can separate those repositories in different packages. Then its possible to create two DB's configurations with different enity manager factory and transaction manager.
For example first config:
#Configuration
#EnableJpaRepositories(basePackages = "com.firstpackage",
entityManagerFactoryRef = "entityManagerFactoryDb1",
transactionManagerRef = "transactionManagerDb1")
public class DB1Config {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryDb1() {
...
}
public JpaTransactionManager transactionManagerDb1() {
...
}
public DataSource dataSourceDb11() {
...
}
Second config would be similar.
You didnt put many details in question, but in case you need to switch databases for same repositories ( for example for different locales ) you can use AbstractRoutingDataSource class which will define determineCurrentLookupKey method.
Does anyone know if Spring has any extensions that allow for configuring its ApplicationContext via JSON (or really any other format) rather than XML? I couldn't find anything in the official docs, but I was wondering if there were any other open source extensions that could allow this.
Just to be clear, I'm not talking about configuring SpringMVC to set up a RESTful JSON-based web service or anything like that, just if it's possible to do Spring app configuration via JSON instead of XML.
As far as I know there is no project to support JSON as configuration source. It should be relatively easy to kick-start, (Spring container has no dependency on XML, it is just a way to construct bean definitions). However it is much more work than you might think.
Note that Spring provides xml-schema to assist you in writing correct XML. You won't get that much in JSON. Also many DSLs were built on top of Spring XML and custom namespaces support (spring-integration, mule-esb and others use it).
If you hate XML (many do), try out Java Configuration, available since 3.0 and improved in 3.1:
#Configuration
public class MyBeans {
#Bean
public Foo foo() {
return new Foo();
}
#Bean
public Bar bar() {
return new Bar(foo());
}
#Bean
public Buzz buzz() {
Buzz buzz = new Buzz();
buzz.setFoo(foo());
return buzz;
}
}
Interesting fact: thanks to some fancy proxying, foo() is called exactly once here, even though referenced twice.
Try JSConf library available on maven central, it's support Properties, HOCON and JSON format.
You can inject values from external file to your service and more !
Sample usage of JavaConfig :
You data stored on file app.conf
{
"root":{
"simpleConf":{
"url":"Hello World",
"port":12,
"aMap":{
"key1":"value1",
"key2":"value2"
},
"aList":[
"value1",
"value2"
]
}}
You service where your configuration must be inject
#Service("service")
public class Service {
#Autowired
private ConfigBean configBean;
}
Declare a interface to access your configuration values from your service
#ConfigurationProperties("root/simpleConf")
public interface ConfigBean {
String getUrl();
int getPort();
Map getAMap();
List getAList();
}
And your Spring configuration bean :
#Configuration
public class ContextConfiguration {
#Bean
public static ConfigurationFactory configurationFactory() {
return new ConfigurationFactory().withResourceName("app.conf") //
.withScanPackage("org.jsconf.core.sample.bean");
}
}