When I try to print the variable that I have autowired, it prints “null” instead of the value I set it to, “Example.” I can’t quite figure out what I’m missing
In my AppConfig class I have:
@Configuration public class ApplicationConfiguration { @Bean public String tableName(){ return "Example"; } }
In my other class, DAOMethods, that I want to autowire the variable in:
@Component public class DAOMethods { @Autowired private String tableName; public void print(){ System.out.println(tableName); } }
Advertisement
Answer
They exist in different packages; With AppConfig living in a config folder and DAOMethods in client->dynamodb->util folder. Config and Client are folders under the main->java folder
The added @Configuration annotation scans for the beans in the current and its subpackages. You need to explicitly tell the application to scan the required packages. So you can do:
@SpringBootApplication (scanBasePackages = {"config", "client"})
OR,
You need to keep the config and other classes which uses that config in same root package. You can put the config folder and client folder under same package, say com.application
and then add the following in your main class:
@SpringBootApplication(scanBasePackages = "com.application")
Now run the application.