spring boot 学习笔记(1)

来源:互联网 发布:淘宝如何开通淘金币 编辑:程序博客网 时间:2024/05/18 03:23

 @ComponentScan@EntityScan 和@SpringBootApplication ,我们通常用它来注释启动类。spring boot的启动类也就是main类一般都放在根文件夹下。比如:

    图片传不上来~你知道吗CSDN?

主程序如下:

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@ComponentScanpublic class App {    public static void main( String[] args )    {SpringApplication app =new SpringApplication(App.class);        app.run(args);    }}

上个会启动spring boot的主程序,初始化bean。这个bean可以是:

@Beanpublic JedisConnectionFactory jedisConnectionFactory(@Qualifier("jedisPoolConfig")JedisPoolConfig jedisPoolConfig){JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();jedisConnectionFactory.setHostName(host);jedisConnectionFactory.setPort(port);jedisConnectionFactory.setTimeout(timeout);jedisConnectionFactory.setPoolConfig(jedisPoolConfig);return jedisConnectionFactory;}

也就是说它在启动完成对这些bean的“装载”。

 @EnableAutoConfiguration 注释默认当前文件夹为搜索的根文件夹。如果你用不带参数的 @ComponentScan 注释在主程序中,它会自动装载@Component@Service@Repository@Controller,做为“spring bean” 。

具体一个例子,我在测试redis时,启动spring boot 需要 执行mutiThread方法,需要默认启动它。因此我在方法前加上@Bean,并且在类前方加上了@configuration注释。这样 @ComponentScan 就能找到@configuration里下配置的@bean,尝试装载bean的同时执行了mutiThread方法。当然这只是为了学习才这样做。去掉 @ComponentScan 和@configuration中的任意一个,mutiThread都不能执行。

@Configuration@EnableConfigurationPropertiespublic 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 blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.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 这个注释属性。

jar运行方式。

你可以借助maven或者gradle打包的你程序,生成可执行jar。我用的maven,执行clean install命令,可以直接install如果是第一次运行,或者用package。

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

1 0
原创粉丝点击