Constants for using in SpringBootApplication - java

Application.java
#SpringBootApplication(scanBasePackages = {"ru.pcask.clients",
"ru.pcask.activities"
})
#EntityScan(value={"ru.pcask.clients",
"ru.pcask.activities"})
#EnableJpaRepositories(value={"ru.pcask.clients",
"ru.pcask.activities"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
"ru.pcask.clients" seems to be a constant. But I don't know how to organize it?
I tried like this:
Constants.java
#Configuration
public class Constants {
private static final String CLIENT = "ru.pcask.clients";
#Bean
public String getClientConst() {
return this.CLIENT;
}
}
But this seems to be a garbage. I don't even know how to use it in #SpringBootApplication.

Related

Reading application.properties in static method

I have the below code when i put some properties statically in SpringApplicationBuilder
#SpringBootApplication(scanBasePackages = { "com" })
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder(Application.class);
parentBuilder.child(RestConfiguration.class, SwaggerConfig.class)
.properties("server.port:9093")).web(WebApplicationType.SERVLET).run(args);
}
}
I want to move the properties to the file application.properties
application.port.query=9093
I used #value to read from the application file, but i get null. Is there another way to read data in a static method?
try something like this
#Configuration
#ConfigurationProperties("application")
class A {
public static int queryPort;
#Value("${port.query:9093}")
public void setQueryPort(final int portQuery){
A.queryPort = portQuery;
}
}
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder(Application.class);
parentBuilder.child(RestConfiguration.class, SwaggerConfig.class)
.properties(A.queryPort)).web(WebApplicationType.SERVLET).run(args);
}
}
The preferable way to what you are trying to achieve is to use the spring bean itself which is the parent of your all configurations org.springframework.core.env.Environment
#SpringBootApplication(scanBasePackages = {"com"})
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext =
SpringApplication.run(Application.class, args);
Environment environment = applicationContext.getBean(Environment.class);
String propertyValue = environment.getProperty("any.property.from.configuration")
}
}
In your use-case, just get the bean of Environment and from Environment object get any property value.

import package Bean for annotation in java

I use the #Bean annotation in java with spring-boot and I can not find the module I need to import.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}

Is there a Spring annotation that replaces ClassPathXmlApplicationContext.getBean?

I have defined a class MyFrontService in a jar, here is how I want to use it:
import blabla.MyFrontService;
public class Main {
public static void main(String[] args) {
MyFrontService.doThis();
}
}
The FrontService serves as an entry point to access other services.
Here is how it is currently defined (and it works).
MyFrontService.java:
public class MyFrontService {
public static void doThis(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/springBeans.xml");
MyService1 myService1 = (MyService1) context.getBean("myService1");
myService1.doSomething();
context.close();
}
}
MyService1.java:
package blabla.service;
#Service("myService1")
public class MyService1 {
public void doSomething(){
// some code
}
}
src/main/resources/META-INF/springBeans.xml:
(...)
<context:annotation-config />
<context:component-scan base-package="blabla.service" />
(...)
I would like to replace the code of MyFrontService.java by something like this:
#MagicAnnotation("what_path?/springBeans.xml")
public class MyFrontService {
#Autowired
private static MyService1 myService1;
public static void doThis(){
myService1.doSomething();
}
}
I've read a lot from other questions on this website and others. It is sometimes said that it's impossible, and sometimes annotations like #Configuration, #Import and others are used but I can't make them work. For example, using
#ImportResource("classpath:META-INF/springBeans.xml")
triggers a NullPointerException when calling myService1.doSomething().
If it is possible to do it, what annotation and what path should I use?
Use Spring Boot framework and you will be able to write smth like this
#Controller
#EnableAutoConfiguration
public class SampleController {
#RequestMapping("/")
#ResponseBody
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
if you mark your class MyFrontService with #Component annotation that should save the headache of doing all the stuff you are doing. if you dont want to add the annotation and dont want to have everything under spring config you can define a class as below.
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
#Override
public void setApplicationContext(
org.springframework.context.ApplicationContext ctx)
throws BeansException {
applicationContext = ctx;
}
}
And then in any class you can do,
ApplicationContext ctx = SpringContextUtil.getApplicationContext();
BeanClass av = ctx.getBean(BeanClass.class);

#Autowired fails in spring boot web project

I have a simple Spring Boot web project, right from a template:
#SpringBootApplication
#RestController
public class HelloWorldRestApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = new Performer();
p.perform();
}
}
I have a test to ensure autowiring works, and in fact it does in this test class (examples come from Spring in Action, 4th):
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
#Autowired
private CDPlayer cdp;
#Test
public void cdShouldNotBeNull(){
assertNotNull(cdp);
}
}
and:
public class Performer {
#Autowired
private CDPlayer cdp;
public void perform(){
System.out.println(cdp);
cdp.play();
}
public CDPlayer getCdp() {
return cdp;
}
public void setCdp(CDPlayer cdp) {
this.cdp = cdp;
}
}
and:
#Component
public class CDPlayer{
public void play(){
System.out.println("play");
}
}
config:
#Configuration
#ComponentScan
public class CDPlayerConfig {
}
However, it doesnt work in HelloWorldRestApplication, I get null.
Adding #ContextConfiguration(classes=CDPlayerConfig.class) doesn't help.
What do I miss?
Try enabling #ComponentScan your packages in your main class and get Performer class instance from ApplicationContext as below:
#SpringBootApplication
#RestController
#ComponentScan({“package.name.1”,”package.name.2”})
public class HelloWorldRestApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(HelloWorldRestApplication.class, args);
Performer p = ctx.getBean(Performer.class);//get the bean by type
p.perform();
}
}

How does a Spring Boot console based application work?

If I am developing a rather simple Spring Boot console-based application, I am unsure about the placement of the main execution code. Should I place it in the public static void main(String[] args) method, or have the main application class implement the CommandLineRunner interface and place the code in the run(String... args) method?
I will use an example as the context. Say I have the following [rudimentary] application (coded to interfaces, Spring style):
Application.java
public class Application {
#Autowired
private GreeterService greeterService;
public static void main(String[] args) {
// ******
// *** Where do I place the following line of code
// *** in a Spring Boot version of this application?
// ******
System.out.println(greeterService.greet(args));
}
}
GreeterService.java (interface)
public interface GreeterService {
String greet(String[] tokens);
}
GreeterServiceImpl.java (implementation class)
#Service
public class GreeterServiceImpl implements GreeterService {
public String greet(String[] tokens) {
String defaultMessage = "hello world";
if (args == null || args.length == 0) {
return defaultMessage;
}
StringBuilder message = new StringBuilder();
for (String token : tokens) {
if (token == null) continue;
message.append(token).append('-');
}
return message.length() > 0 ? message.toString() : defaultMessage;
}
}
The equivalent Spring Boot version of Application.java would be something along the lines:
GreeterServiceImpl.java (implementation class)
#EnableAutoConfiguration
public class Application
// *** Should I bother to implement this interface for this simple app?
implements CommandLineRunner {
#Autowired
private GreeterService greeterService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println(greeterService.greet(args)); // here?
}
// Only if I implement the CommandLineRunner interface...
public void run(String... args) throws Exception {
System.out.println(greeterService.greet(args)); // or here?
}
}
You should have a standard loader:
#SpringBootApplication
public class MyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyDemoApplication.class, args);
}
}
and implement a CommandLineRunner interface with #Component annotation
#Component
public class MyRunner implements CommandLineRunner {
#Override
public void run(String... args) throws Exception {
}
}
#EnableAutoConfiguration will do the usual SpringBoot magic.
UPDATE:
As #jeton suggests the latest Springboot implements a straight:
spring.main.web-application-type=none
spring.main.banner-mode=off
See docs at 72.2

Categories

Resources