The @Service
annotation needs to be removed and the bean must be created in a @Configuration
class with a @Bean
annotated method returning that class type.
//Test.java
package com.abc;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@RequiredArgsConstructor
@ToString
public class Test {
private final String str;
private String str5;
}
//DemoApplication.java
package com.abc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
Test buildTest(@Value("${xyz}") String value) {
return new Test(value);
}
}
note: @SpringBootApplication
implies @Configuration
//DemoApplicationTests.java
package com.abc;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
com.abc.Test test;
@Test
void contextLoads() {
System.out.println(test);
}
}
#application.properties
xyz=print me
Result:
Test(str=print me, str5=null)
private final SomeRepository repository
– Chlorohydrin@Value("${xyz"})
on the constructor paramter. You can use lombok, but it gets really messy to apply annotations to the consturctor. SeeonConstructor
documentation, – Attalie