對於springboot來說,它會把當前應用程序所在的包裝載到ioc容器里,讓使用者可以直接Autowired注入它們,一般的項目結果是這樣的,這個項目包下有main方法,它將會把nacosdemo這個包里面所有的bean都掃描出來,然后在程序啟動時,nacosdemo里的bean就會被自動注冊了。
目前我們做一個測試,在nacosdemo包外層再建立一個包common,在里面寫個組件,然后在nacosdemo里去使用它,整個項目結構如下
這時,項目啟動后,是無法加載到你的bean的,因為它不會被掃描到,解決方法是把它添加到掃描包列表里
@SpringBootApplication(scanBasePackages = {"com.lind.nacosdemo", "com.lind.common"})
@EnableDiscoveryClient
public class NacosDemoApplication {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosDemoApplication.class, args);
String userName = applicationContext.getEnvironment().getProperty("user.name");
String userAge = applicationContext.getEnvironment().getProperty("user.age");
System.err.println("user name :" + userName + "; age: " + userAge);
}
}
在添加時要注冊,當前包的名稱也要加上,否則當前包也會被覆蓋的,這一點要清楚。
測試的代碼
common里的組件bean
@Component
public class RedisConfig {
public void print() {
System.out.println("hello redis!");
}
}
canosdemo包里調用它
@Autowired
RedisConfig redisConfig;
@RequestMapping("/get")
public String get() {
redisConfig.print();
return username;
}
結果如圖,我們的方法被調用到了
這種方法雖然實現了我們的功能,但需要在程序的入口維護一坨坨包名,很不友好,下次我們說對這塊進行重構。