1

I have a simple Spring Boot project with the following directory structure:

.
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       ├── example
│   │   │       │   └── base
.   .   │       │       ├── db
.   .   │       │       │   ├── entity
.   .   │       │       │   │   └── SomeComponent.java
.   .   │       │       │   ├── repository
        │       │       │   └── util
        │       │       └── development
        │       └── MainApplication.java     
        └── resources
            └── application.properties

The MainApplication is basically the default one:

package com.example.base;

@SpringBootApplication
public class MainApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(MainApplication.class);
        application.run(args);
    }
    ...

In MainApplication.java I actually got a valid reverence to the environment and I can actually access it properly, however I'm getting null in SomeComponent.class

package com.example.base.db.entity;

@Component
public class SomeComponent {

    @Autowired
    private Environment env;

    public SomeComponent() {}

    public void foo() {
        System.out.println(env);
    }

}

This is supposed to work fine because SomeComponent.java is in a sub package of com.example.base which should be scanned automatically by the default configuration of @SpringBootApplication right ? I don't see why this is failing.

Thanks in advance, any help will be appreciated

sam
  • 1,800
  • 1
  • 25
  • 47
William Añez
  • 730
  • 6
  • 25

2 Answers2

1

Thanks for your comments, I found myself the issue, I was instantiating my component using new (as a rookie mistake). I added the following Bean to my MainApplication.class and everything started flowing.

@Bean
public SomeComponent someComponent() {
    return new SomeComponent();
}

And when I need it I just use context.getBean(SomeComponent.class)

William Añez
  • 730
  • 6
  • 25
0

Spring Boot has simplified this process. You can access values from properties file with the following codes:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Check this stackoverflow post for more reference.

sam
  • 1,800
  • 1
  • 25
  • 47