Własne zmienne konfiguracyjne

0

Zaczytany w książce Spring in action fifth edition spróbowałem postawić swoje własne zmienne konfiguracyjne ze spring bootem .

Proszę vardzo:

@Component
@ConfigurationProperties(prefix = "myprops")
public class MyClass {

    private int myvar1;

    // Getters and setters...
}

application.properties:

myprops.myvar1=3333

MyClass.getMyvar1() powinien zwrócić 3333 a wciąż zwraca defaultowe 0.

@EnableConfigurationProperties(MyClass.class)
@SpringBootApplication
public class Demo1Application {
    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }

    @Bean
    public CommandLineRunner foo(ApplicationContext ctx) {
        return args -> {
            MyClass mc = new MyClass();
            int x = mc.getMyvar1();
            System.out.println(x);
        };
    }
}
5

new MyClass(); ;] srsly? I jak ci niby Spring ma tą klasę zinstrumentować? Magią? Szkoda słów. Skoro już masz przy tej klasie @Component to Spring zrobi z niej beana (jeśli pakiet jest w skanie) i bierzesz sobie ten zinstrumentowany obiekt przez @Inject

    @Bean
    @Inject
    public CommandLineRunner foo(ApplicationContext ctx, MyClass mc) {
        return args -> {
            int x = mc.getMyvar1();
            System.out.println(x);
        };
    }

Ale odradzam takie machinacje bo potem coś takiego znaleźć w kodzie to dramat bo nawet string search nie pomaga. Wstrzykuj te propertiesy po ludzku:

@Value("${myprops.myvar1}")
int myvar1;

1 użytkowników online, w tym zalogowanych: 0, gości: 1