标签:
@ComponentScan, @EntityScan 和@SpringBootApplication ,我们通常用它来注释启动类。spring
boot的启动类也就是main类一般都放在根文件夹下。比如:
package testRedis.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
/**
* Hello world!
*/
@EnableAutoConfiguration
@ComponentScan
public class App
{
public static void main( String[] args )
{
SpringApplication app =new SpringApplication(App.class);
app.run(args);
}
}
上个会启动spring boot的主程序,初始化bean。 @EnableAutoConfiguration 注释默认当前文件夹为搜索的根文件夹。如果你用不带参数的 @ComponentScan 注释在主程序中,它会自动装载@Component, @Service, @Repository, @Controller做为“spring
bean” 。
具体一个例子,我在测试redis时,启动spring boot 需要 执行mutiThread方法,需要默认启动它。因此我在方法前加上@Bean,并且在类前方加上了@configuration注释。这样 @ComponentScan 就能找到@configuration里下配置的@bean,尝试装载bean的同时执行了mutiThread方法。当然这只是为了学习才这样做。去掉 @ComponentScan 和@configuration中的任意一个,mutiThread都不能执行。
@Configuration
@EnableConfigurationProperties
public class testCase1 {
@Autowired
@Qualifier("taskExcute")
private TaskExcute taskExcute;
@Value("${cl.size:1000000}")
private int size;
@Bean
public String mutiThread(){
Map<String,Object> map=new HashMap<String,Object>();
for(int i=size;i>0;i--){
map.put("name"+i, "foo");
}
try {
taskExcute.dotasks(map);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "hello world!";
}
}
用 @ComponentScan 就不需要指定 basePackage 。如果你的主main程序在根文件夹的话@SpringBootApplication 也可以起同样的效果。
spring boot会基于你的class path 下的jar包依赖自动配置你的spring程序。具体什么情况,有待深入研究。
这个功能自动配置加载的功能,可以通过以下方式禁掉。
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { }
如果这个类没有在 classpath, 你可以用 excludeName 这个注释属性。
你可以借助maven或者gradle打包的你程序,生成可执行jar。我用的maven,执行clean install命令,可以直接install如果是第一次运行,或者用package。
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
标签:
原文地址:http://blog.csdn.net/landai2011/article/details/51273558