get value config server spring boot - java

I use spring boot and jboss eap 6.4 for deploying application. in my pom.xml set config server. the file name is letter-printing-eap-generator.yml. this file contains value. how to get the data from this file? or can you give me the references? because I had find but no one match with my case.
pom.xml:
<properties>
<config.server>http://10.170.49.103/configserver</config.server>
</properties>
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>7.9.Final</version>
<configuration>
<jbossHome>${jboss.home}</jbossHome>
<serverArgs>
<serverArg>-Dspring.profiles.active=${run.profiles}</serverArg>
<serverArg>-Dspring.cloud.config.uri=${config.server}</serverArg>
</serverArgs>
</configuration>
</plugin>
application.properties:
spring.application.name=letter-printing-eap-generator
bootstrap.yml:
spring.jmx.default-domain: letter-printing-eap-generator

#Service
public class SomeServiceServiceImpl implements SomeService{
#Value("${letter-printing-eap-generator}")
private String letterPrintingEapGenerator;
//methods
}

In spring boot thereis annotation #Value
You can use it to get values from you properties files. It works like this: #Value("${letter-printing-eap-generator}")

Related

How to set JBoss Wildfly context root with XML-less Spring web application?

Having a Spring application with Maven where all the configuration is done in Java (all configuration previously stored in web.xml is now in annotated #Configuration files or in WebAppInitializer that extends AbstractAnnotationConfigDispatcherServletInitializer), how can I set the context root for my application in JBoss Wildfly? The app has no web.xml, nor jboss-web.xml .
When the app used XML configuration the context root was set in jboss-web.xml like this:
<jboss-web>
<context-root>mywebcontextroot</context-root>
</jboss-web>
JBoss wildfly defaults the context root to the name of the war file. Setting the name of the war file to the desired value (web context root) in Maven solves the issue:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>mywebcontextroot</warName>
</configuration>
</plugin>
More detailed answer by #Nikhil Bide can be found here.

Access Maven property "developers" in application.yml (Spring Boot)

I want to have the developer, which is defined in the pom.xml with the tag to appear in the application.yml after the build process. Somehow it is working with all attributes but developers.
This is in a Spring Boot project, I want the attributes to be filled during the build process.
This is an excerpt of the pom.xml
<description>my description</description>
<developers>
<developer>
<id>12345</id>
<name>John Doe</name>
<email>john#doe.com</email>
</developer>
</developers>
This is in application.yml
info:
description: "#project.description#"
developer: "#project.developers[0].id#"
It works for description, but not for developer. I tried many variations, e.g. ${..}, "#project.developers.0.id". Nothing seems to be working.
If anybody has an idea, I would be very grateful.
You can read the developer id or email address or any values from the pom.xml with this elegant way:
Generate the build-info.properties with the default data plus your additional data
Read values from this file easily with Spring via the BuildProperties.
pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<developer>${project.developers[0].email}</developer>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
This will produce a build-info.properties file under the META-INF directory with the following content:
build.artifact=<artifactId-from-pom>
build.group=<groupId-from-pom>
build.name=<name-from-pom>
build.time=<build-time>
build.version=<version-from-pom>
build.developer=<email-of-the-first-developer-from-pom>
Then you can read values with Spring:
#Configuration
public class OpenApiConfiguration {
#Autowired
private BuildProperties buildProperties;
#Bean
public OpenAPI customOpenAPI()) {
return new OpenAPI().info(new Info()
.title(...)
.version(buildProperties.getVersion())
.contact(new Contact().email(buildProperties.get("developer"))));
}
}
To read:
Spring Boot Maven Plugin
BuildProperties
I hope that this will help you.
Add it on the property and use on pom and property file, example:
<properties>
<team.name>John Doe</team.name>
</properties>
Use on developer data:
<developers>
<developer>
<name>${team.name}</name>
...
And in the application use the property:
description: "#team.name#"

Activate profiles for spring boot test using application.properties file

I have been using Spring Boot and TestNG for my test framework and so far my tests were configured to use only one default application.properties file which is under src/main/resource. Now I want to configure them for different environments - ci/stage etc. I have used spring documentation to activate the profiles from pom.xml file.
<profiles>
<profile>
<id>ci</id>
<properties>
<activeProfile>ci</activeProfile>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
I have for two properties files under src/main/resources - application.properties and application-ci.properties. (The is the naming convention suggested by spring documentation. application-{activatedprofile}.properties).
The application.properties have got a placeholder -
spring.profiles.active=#activeProfile#
The #activeProfile# will get replaced with the value of activeProfile in the pom.xml file.And uptil that it is working.
In my #Configuration class I have a annotation as below and I am expecting that the ${spring.profiles.active} value gets replaced with value - ci.
#PropertySource("classpath:application-${spring.profiles.active}.properties")
I am getting following error:
java.lang.IllegalArgumentException: Could not resolve placeholder
'spring.profiles.active' in value
"classpath:application-${spring.profiles.active}.properties"
I am using maven and testng to run my project. I am doing something incorrect let me know how can I resolve it.
First of all, the maven profile is not the same as the spring profile. In the code snippet provided you are setting the maven profile, not the spring profile.
To pass a specific spring profile during your test phase you can use the surefire plugin. In the code snippet below you would be passing in the system property spring.profiles.active as ci. This is equivalent to setting the value in your application.properties file.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<systemPropertyVariables>
<spring.profiles.active>ci</spring.profiles.active>
</systemPropertyVariables>
</configuration>
</plugin>
Secondly, spring will automatically load the property sources based on the active spring profile. In your example, spring will first load application.properties then it will apply application-ci.properties on top of it. As a result
#PropertySource("classpath:application-${spring.profiles.active}.properties")
is not needed.
If you have a configuration class that is specific to an active profile then you can add #ActiveProfiles("ci") to your configuration class and it will only use that class when the profile ci is active.
Lastly, you do not need the property spring.profiles.active=#activeProfile# in your application.properties files as this be passed in from the surefire plugin in maven.

How to fully disable swagger-ui in spring-boot?(/swagger-ui.html should return 404)

I have read following topic:
Disabling Swagger with Spring MVC
and I wrote:
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.project.name.controller"))
.paths(PathSelectors.ant("/api/**"))
.build()
.apiInfo(apiInfo())
.enable(false);
}
But in case if I try to access swagger ui: localhost:8080/swagger-ui.html
I see
It looks not accurate. Can I fully disabled this URL ? 404 for example or something like this.
My answer is similar to the answer provided earlier with a slight difference. I usually create a separate spring profile named swagger. When I want to enable Swagger, l pass the following VM flag while starting my application, -Dspring.profiles.active=swagger. Here is an example of my Swagger configuration,
#Profile(value = {"swagger"})
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
...
}
Next time when you try to access swagger-ui.html without swagger profile, you will get an empty Swagger screen but not 404.
If you don't want to load the static Swagger UI page at all, you can write a simple controller as shown below,
#Profile("!swagger")
#RestController
#Slf4j
public class DisableSwaggerUiController {
#RequestMapping(value = "swagger-ui.html", method = RequestMethod.GET)
public void getSwagger(HttpServletResponse httpResponse) throws IOException {
httpResponse.setStatus(HttpStatus.NOT_FOUND.value());
}
}
Now if you try to access swagger-ui.html without swagger profile, you will get a 404.
with swagger 3.0.0 version you can add springfox.documentation.enabled=false in corresponding environment profile application.properties file.
For example, I have added this to application-prod.properties to disable in production (while running the app you must specify the profile using VM args like -Dspring.profiles.active=prod)
You can externalize the #EnableSwagger2 to its own #Configruation and load it conditionally via a property or profile. e.g.
#Profile("!production")
#Configuration
#EnableSwagger2
public class SwaggerConfiguration{
//Additional Swagger Beans
}
this would activate swagger for any profile that isn't production.
Adding onto #Hayden's answer (I don't have enough points to comment..)
According to the springdoc documentation, you can disable both the springdoc api endpoints and swagger-ui using the following properties:
https://springdoc.org/#disabling-the-springdoc-openapi-endpoints
# Disabling the /v3/api-docs endpoint
springdoc.api-docs.enabled=false
https://springdoc.org/#disabling-the-swagger-ui
# Disabling the swagger-ui
springdoc.swagger-ui.enabled=false
If you dont have Swagger annotations inside controllers... just exclude SwaggerConfig.class and swagger dependencies on build
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<excludes>
<exclude>com/company/app/SwaggerConfig.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</exclude>
<exclude>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</exclude>
</excludes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
For SpringDoc users, add this to your application.properties
springdoc.api-docs.enabled=false
To disable Swagger only when the prod profile is active, add it to your application-prod.properties instead
For those that use the code gen:
#Controller
#Profile({"dev", "staging"})
public class HomeController {
#RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
And add the file to you .swagger-codegen-ignore else your changes are overwritten on the next maven build
When using springdoc-openapi-ui dependency one can disable swagger-ui through the property:
springdoc.swagger-ui.enabled=false
as stated in Spring Doc FAQ.
In latest version of spring boot you can add this in yout application.yml :
springdoc:
swagger-ui:
enabled: false
api-docs:
enabled: false
So that swagger-ui key is used to disable the swagger interface and api-docs one is used to disable the route on which the JSON describing your API is served.
In my config I have a prod profile wich reads an application-prod.yml containing those lines.
Just remove dependency.
<!--<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>-->
It does not affect compiling.

Configure Java EE 6 for dev/QA/prod

I have a Java EE 6 app that I build with Maven, code in NetBeans 7 and deploy on GlassFish 3.1.2. As I near completion, I find myself deploying demo builds.
The problem is that I don't have any dead easy way to build for different environment such as dev, QA, demo, prod, etc. For some stuff, I've been using a Java class with a bunch of static getters that return values based on the value of an environment constant. But this doesn't help me with conditionally setting
javax.faces.PROJECT_STAGE (web.xml)
database credentials (glassfish-resources.xml)
mail servers (glassfish-resources.xml)
JPA logging level (persistence.xml)
and probably a number of other things I can't think about now that are scattered across XML files.
Is there any way to define multiple versions of these configuration files and just set a flag at build time to select the environment, while defaulting to dev when no environment is specified? Is there a way I could make Maven work for me in this instance?
You can use maven to achieve that. Especially using resource filtering.
First, you can define list of profiles:
<profiles>
<profile>
<id>dev</id>
<properties>
<env>development</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault> <!-- use dev profile by default -->
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<env>production</env>
</properties>
</profile>
</profiles>
Then the resources that you need to filter:
<build>
<outputDirectory>${basedir}/src/main/webapp/WEB-INF/classes</outputDirectory>
<filters>
<filter>src/main/filters/filter-${env}.properties</filter> <!-- ${env} default to "development" -->
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
And then your custom properties based on profiles in src/main/filters directory:
filter-development.properties
# profile for developer
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:web
and
filter-production.properties
# profile for production
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/web?createDatabaseIfNotExist=true
to use production profile, you can package war using mvn clean package -Pprod command.
Here you can see the sample project that use profile in maven.
This is not direct response to question. This explain diff strategy to manage env properties
One other way to manage properties for diff env is using the database to store the properties. This way you have only need to manage the config of the DB. Based on which DB you are pointing you can load the properties from that DB. If you are using spring than spring provides PropertyPlaceholderConfigurer which can initialize the properties from DB. This approach allows you to change the property value without doing a build.
This approach is useful if you want to promote the artifact tested by QA\Testing team. In this case DB configuration will not be part of artifact generated by build process.
If you need to configure web.xml check this how-to:
https://community.jboss.org/docs/DOC-19076
It uses same method (resource filtering) as described in another answers.

Categories

Resources