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();
}
}
Related
Kindly help with accessing values from yaml file in Sprint Boot. I am getting error as below. I am able to access value of filepath1 variable in AppConfig class but not sure why its giving the error.
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'filepath1' in value "${filepath1}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
My main class is as follows
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args)
{
System.out.println("Starting ");
SpringApplication.run(DemoApplication.class, args);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApplication.class);
Employee employee = applicationContext.getBean(Employee.class);
System.out.println("Exiting ");
}
}
Config class is as follows
#Slf4j
#Configuration
#ComponentScan("com.vish.springbootdemo.demo")
public class AppConfig
{
#Value("${filepath1}")
private String file1;
#Bean
public Employee employee()
{
System.out.println("file1 is " + file1);
return new Employee();
}
}
Here is the application.yml
filepath1: "vish"
The problem is that in the main method, you are creating your own application context:
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(DemoApplication.class);
This will be completely separate from the application context that Spring Boot creates for you, and won't have the configuration properties from application.yml in it.
Instead of doing this, use the application context that Spring Boot provides. Even better: Don't explicitly lookup a bean in the application context, but let Spring Boot autowire the bean for you.
Something like this:
#SpringBootApplication
public class DemoApplication implements CommandLineRunner {
#Autowired
private Employee employee;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Employee: " + employee);
}
}
AppConfig:
#Configuration
public class AppConfig {
#Value("${filepath1}")
private String file1;
#Bean
public Employee employee() {
System.out.println("file1 is " + file1);
return new Employee();
}
}
Start your spring boot application like this:
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
Resources folder should contain application.yml.
filepath1: vish
Inject your bean with #Autowired
#Component
class AnotherComponent {
#Autowired Employee employee;
}
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.
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.
Main:
#SpringBootApplication
#ComponentScan(basePackageClasses = Application.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Test class:
public class Test {
#Bean
public Test test(){
return new Test();
}
}
and when I'm trying to autowire it then i got this exception:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field test in TestWithAutowire required a bean of type 'Test' that could not be found.
Action:
Consider defining a bean of type 'rcms.backend.exception.Test' in your configuration.
Process finished with exit code 1
There is something hat I'm doing wrong, but I can't find it out.
You can create a new configuration, let's say SpringConfiguration,
package my.pkg.config;
#Configuration
public class SpringConfiguration {
#Bean
public Test test(){
return new Test();
}
}
In your Application class, you can add the #ComponentScan annotation with the base packages where you would like Spring to scan for classes,
#SpringBootApplication
#ComponentScan(basePackageClasses = {"my.pkg.config", "my.pkg.example"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Now you can autowire Test in any Spring component. For example,
package my.pkg.example;
#Component
public class TestExample {
#Autowired
private Test tst;
}
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();
}
}