springboot入门

1.  今日大纲

1、  了解Spring的发展

2、  掌握Spring的java配置方式

3、  学习Spring Boot

4、  使用Spring Boot来改造购物车系统

2.  Spring的发展

2.1.  Spring1.x 时代

在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换。

2.2.  Spring2.x时代

随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml配置文件,同时也大大简化了项目的开发。

 

那么,问题来了,究竟是应该使用xml还是注解呢?

 

最佳实践:

1、  应用的基本配置用xml,比如:数据源、资源文件等;

2、  业务开发用注解,比如:Service中注入bean等;

2.3.  Spring3.x到Spring4.x

从Spring3.x开始提供了Java配置方式,使用Java配置方式可以更好的理解你配置的Bean,现在我们就处于这个时代,并且Spring4.x和Spring boot都推荐使用java配置的方式。

3.  Spring的Java配置方式

Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置。

3.1.  @Configuration 和 @Bean

Spring的Java配置方式是通过 @Configuration和 @Bean 这两个注解实现的:

1、@Configuration 作用于类上,相当于一个xml配置文件;

2、@Bean 作用于方法上,相当于xml配置中的<bean>;

3.2.  示例

该示例演示了通过Java配置的方式进行配置Spring,并且实现了Spring IOC功能。

3.2.1.  创建工程以及导入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <groupId>cn.itcast.springboot</groupId>

   <artifactId>itcast-springboot</artifactId>

   <version>1.0.0-SNAPSHOT</version>

   <packaging>war</packaging>

 

   <dependencies>

      <dependency>

         <groupId>org.springframework</groupId>

         <artifactId>spring-webmvc</artifactId>

         <version>4.3.7.RELEASE</version>

      </dependency>

      <!-- 连接池 -->

      <dependency>

         <groupId>com.jolbox</groupId>

         <artifactId>bonecp-spring</artifactId>

         <version>0.8.0.RELEASE</version>

      </dependency>

   </dependencies>

   <build>

      <finalName>${project.artifactId}</finalName>

      <plugins>

         <!-- 资源文件拷贝插件 -->

         <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-resources-plugin</artifactId>

            <configuration>

               <encoding>UTF-8</encoding>

            </configuration>

         </plugin>

         <!-- java编译插件 -->

         <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-compiler-plugin</artifactId>

            <configuration>

               <source>1.7</source>

               <target>1.7</target>

               <encoding>UTF-8</encoding>

            </configuration>

         </plugin>

      </plugins>

      <pluginManagement>

         <plugins>

            <!-- 配置Tomcat插件 -->

            <plugin>

               <groupId>org.apache.tomcat.maven</groupId>

               <artifactId>tomcat7-maven-plugin</artifactId>

               <version>2.2</version>

            </plugin>

         </plugins>

      </pluginManagement>

   </build>

</project>

3.2.2.  编写User对象

publicclass User {

 

    private String username;

 

    private String password;

 

    private Integer age;

 

    public String getUsername() {

        returnusername;

    }

 

    publicvoid setUsername(String username) {

        this.username = username;

    }

 

    public String getPassword() {

        returnpassword;

    }

 

    publicvoid setPassword(String password) {

        this.password = password;

    }

 

    public Integer getAge() {

        returnage;

    }

 

    publicvoid setAge(Integer age) {

        this.age = age;

    }

 

}

 

3.2.3.  编写UserDAO 用于模拟与数据库的交互

publicclass UserDAO {

   

    public List<User>queryUserList(){

        List<User> result = newArrayList<User>();

        // 模拟数据库的查询

        for (inti = 0; i < 10; i++) {

            User user = new User();

            user.setUsername("username_" + i);

            user.setPassword("password_" + i);

            user.setAge(i + 1);

            result.add(user);

        }

        returnresult;

    }

 

}

3.2.4.  编写UserService 用于实现User数据操作业务逻辑

@Service

publicclass UserService {

 

    @Autowired // 注入Spring容器中的bean对象

    private UserDAO userDAO;

 

    public List<User>queryUserList() {

        // 调用userDAO中的方法进行查询

        returnthis.userDAO.queryUserList();

    }

 

}

3.2.5.  编写SpringConfig 用于实例化Spring容器

@Configuration//通过该注解来表明该类是一个Spring的配置,相当于一个xml文件

@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig"//配置扫描包

publicclass SpringConfig{

   

    @Bean// 通过该注解来表明是一个Bean对象,相当于xml中的<bean>

    public UserDAO getUserDAO(){

        returnnew UserDAO(); // 直接new对象做演示

    }

   

}

3.2.6.  编写测试方法 用于启动Spring容器

publicclass Main {

   

    publicstaticvoid main(String[] args) {

        // 通过Java配置来实例化Spring容器

        AnnotationConfigApplicationContext context = newAnnotationConfigApplicationContext(SpringConfig.class);

       

        // Spring容器中获取Bean对象

        UserService userService = context.getBean(UserService.class);

       

        // 调用对象中的方法

        List<User> list = userService.queryUserList();

        for (User user : list) {

            System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPassword());

        }

       

        // 销毁该容器

        context.destroy();

    }

 

}

3.2.7.  测试效果

3.2.8.  小结

从以上的示例中可以看出,使用Java代码就完美的替代xml配置文件,并且结构更加的清晰。

3.3.  实战

3.3.1.  读取外部的资源配置文件

通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法:

 

@Configuration//通过该注解来表明该类是一个Spring的配置,相当于一个xml文件

@ComponentScan(basePackages = "cn.itcast.springboot.javaconfig"//配置扫描包

@PropertySource(value= { "classpath:jdbc.properties"})

publicclass SpringConfig {

   

    @Value("${jdbc.url}")

    private String jdbcUrl;

   

    @Bean// 通过该注解来表明是一个Bean对象,相当于xml中的<bean>

    public UserDAO getUserDAO(){

        returnnew UserDAO(); // 直接new对象做演示

    }

   

}

 

思考:

1、  如何配置多个配置文件?

2、  如果配置的配置文件不存在会怎么样?

3.3.2.  配置数据库连接池

导入依赖:

<!-- 连接池 -->

      <dependency>

         <groupId>com.jolbox</groupId>

         <artifactId>bonecp-spring</artifactId>

         <version>0.8.0.RELEASE</version>

      </dependency>

 

之前的Spring xml配置:

    <!-- 定义数据源 -->

   <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"

      destroy-method="close">

      <!-- 数据库驱动 -->

      <property name="driverClass"value="${jdbc.driverClassName}" />

      <!-- 相应驱动的jdbcUrl -->

      <property name="jdbcUrl"value="${jdbc.url}" />

      <!-- 数据库的用户名 -->

      <property name="username"value="${jdbc.username}" />

      <!-- 数据库的密码 -->

      <property name="password"value="${jdbc.password}" />

      <!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->

      <property name="idleConnectionTestPeriod"value="60" />

      <!-- 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 -->

      <property name="idleMaxAge"value="30" />

      <!-- 每个分区最大的连接数 -->

      <!--

         判断依据:请求并发数

       -->

      <property name="maxConnectionsPerPartition"value="100" />

      <!-- 每个分区最小的连接数 -->

      <property name="minConnectionsPerPartition"value="5" />

   </bean>

 

参考xml配置改造成java配置方式:

 

    @Value("${jdbc.url}")

    private String jdbcUrl;

 

    @Value("${jdbc.driverClassName}")

    private String jdbcDriverClassName;

 

    @Value("${jdbc.username}")

    private String jdbcUsername;

 

    @Value("${jdbc.password}")

    private String jdbcPassword;

 

    @Bean(destroyMethod = "close")

    public DataSource dataSource() {

        BoneCPDataSource boneCPDataSource = newBoneCPDataSource();

        // 数据库驱动

        boneCPDataSource.setDriverClass(jdbcDriverClassName);

        // 相应驱动的jdbcUrl

        boneCPDataSource.setJdbcUrl(jdbcUrl);

        // 数据库的用户名

        boneCPDataSource.setUsername(jdbcUsername);

        // 数据库的密码

        boneCPDataSource.setPassword(jdbcUsername);

        // 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0

        boneCPDataSource.setIdleConnectionTestPeriodInMinutes(60);

        // 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0

        boneCPDataSource.setIdleMaxAgeInMinutes(30);

        // 每个分区最大的连接数

        boneCPDataSource.setMaxConnectionsPerPartition(100);

        // 每个分区最小的连接数   

        boneCPDataSource.setMinConnectionsPerPartition(5);

        returnboneCPDataSource;

}

 

思考:如何使用该DataSource对象?

4.  Spring Boot

4.1.  什么是Spring Boot

4.2.  Spring Boot的优缺点

4.3.  快速入门

4.3.1.  设置spring boot的parent

<parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.5.2.RELEASE</version>

   </parent>

 

说明:Spring boot的项目必须要将parent设置为spring boot的parent,该parent包含了大量默认的配置,大大简化了我们的开发。

4.3.2.  导入spring boot的web支持

<dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

      </dependency>

4.3.3.  添加Spring boot的插件

<plugin>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-maven-plugin</artifactId>

         </plugin>

4.3.4.  编写第一个Spring Boot的应用

@Controller

@SpringBootApplication

@Configuration

publicclass HelloApplication {

   

    @RequestMapping("hello")

    @ResponseBody

    public String hello(){

        return"hello world";

    }

   

    publicstaticvoid main(String[] args) {

        SpringApplication.run(HelloApplication.classargs);

    }

 

}

 

代码说明:

1、@SpringBootApplication:Spring Boot项目的核心注解,主要目的是开启自动配置。;

2、@Configuration:这是一个配置Spring的配置类;

3、@Controller:标明这是一个SpringMVC的Controller控制器;

4、main方法:在main方法中启动一个应用,即:这个应用的入口;

4.3.5.  启动应用

在Spring Boot项目中,启动的方式有两种,一种是直接run Java Application另外一种是通过Spring Boot的Maven插件运行。

 

第一种:

 

第二种:

 

启动效果:

 

看到如下信息就说明启动成功了:

INFO 6188 --- [           main]c.i.springboot.demo.HelloApplication    : Started HelloApplication in 3.281 seconds (JVM running for 3.601)

4.3.6.  测试

打开浏览器,输入地址:

 

效果:

 

是不是很Easy?

4.4.  Spring Boot的核心

4.4.1.  入口类和@SpringBootApplication

Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序的入口方法。

 

@SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解:

 

 

该注解主要组合了以下注解:

1.       @SpringBootConfiguration:这是Spring Boot项目的配置注解,这也是一个组合注解:

在Spring Boot项目中推荐使用@ SpringBootConfiguration替代@Configuration

2.       @EnableAutoConfiguration:启用自动配置,该注解会使SpringBoot根据项目中依赖的jar包自动配置项目的配置项:

a)      如:我们添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,Spring Boot就会自动配置tomcat和SpringMVC

3.       @ComponentScan:默认扫描@SpringBootApplication所在类的同级目录以及它的子目录。

4.4.2.  关闭自动配置

通过上述,我们得知,Spring Boot会根据项目中的jar包依赖,自动做出配置,Spring Boot支持的自动配置如下(非常多):

 

如果我们不需要Spring Boot自动配置,想关闭某一项的自动配置,该如何设置呢?

 

比如:我们不想自动配置Redis,想手动配置。

 

当然了,其他的配置就类似了。

4.4.3.  自定义Banner

启动Spring Boot项目后会看到这样的图案:

 

这个图片其实是可以自定义的:

1.       打开网站:http://patorjk.com/software/taag/#p=display&h=3&v=3&f=4Max&t=itcast%20Spring%20Boot

2.       拷贝生成的字符到一个文本文件中,并且将该文件命名为banner.txt

3.       将banner.txt拷贝到项目的resources目录中:

4.       重新启动程序,查看效果:


好像没有默认的好看啊!!!

 

如果不想看到任何的banner,也是可以将其关闭的:

4.4.4.  全局配置文件

Spring Boot项目使用一个全局的配置文件application.properties或者是application.yml,在resources目录下或者类路径下的/config下,一般我们放到resources下。

 

1、  修改tomcat的端口为8088

重新启动应用,查看效果:

2、  修改进入DispatcherServlet的规则为:*.html

测试:



 

更多的配置:

 

# ===================================================================
# COMMON SPRING BOOT PROPERTIES
#
# This sample file is provided as a guideline. Do NOT copy it in its
# entirety to your own application.               ^^^
# ===================================================================
 
 
# ----------------------------------------
# CORE PROPERTIES
# ----------------------------------------
 
# BANNER
banner.charset=UTF-8 # Banner file encoding.
banner.location=classpath:banner.txt # Banner file location.
banner.image.location=classpath:banner.gif # Banner image file location (jpg/png can also be used).
banner.image.width= # Width of the banner image in chars (default 76)
banner.image.height= # Height of the banner image in chars (default based on image height)
banner.image.margin= # Left hand image margin in chars (default 2)
banner.image.invert= # If images should be inverted for dark terminal themes (default false)
 
# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
 
# AOP
spring.aop.auto=true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class=false # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false).
 
# IDENTITY (ContextIdApplicationContextInitializer)
spring.application.index= # Application index.
spring.application.name= # Application name.
 
# ADMIN (SpringApplicationAdminJmxAutoConfiguration)
spring.application.admin.enabled=false # Enable admin features for the application.
spring.application.admin.jmx-name=org.springframework.boot:type=Admin,name=SpringApplication # JMX name of the application admin MBean.
 
# AUTO-CONFIGURATION
spring.autoconfigure.exclude= # Auto-configuration classes to exclude.
 
# SPRING CORE
spring.beaninfo.ignore=true # Skip search of BeanInfo classes.
 
# SPRING CACHE (CacheProperties)
spring.cache.cache-names= # Comma-separated list of cache names to create if supported by the underlying cache manager.
spring.cache.caffeine.spec= # The spec to use to create caches. Check CaffeineSpec for more details on the spec format.
spring.cache.couchbase.expiration=0 # Entry expiration in milliseconds. By default the entries never expire.
spring.cache.ehcache.config= # The location of the configuration file to use to initialize EhCache.
spring.cache.guava.spec= # The spec to use to create caches. Check CacheBuilderSpec for more details on the spec format.
spring.cache.infinispan.config= # The location of the configuration file to use to initialize Infinispan.
spring.cache.jcache.config= # The location of the configuration file to use to initialize the cache manager.
spring.cache.jcache.provider= # Fully qualified name of the CachingProvider implementation to use to retrieve the JSR-107 compliant cache manager. Only needed if more than one JSR-107 implementation is available on the classpath.
spring.cache.type= # Cache type, auto-detected according to the environment by default.
 
# SPRING CONFIG - using environment property only (ConfigFileApplicationListener)
spring.config.location= # Config file locations.
spring.config.name=application # Config file name.
 
# HAZELCAST (HazelcastProperties)
spring.hazelcast.config= # The location of the configuration file to use to initialize Hazelcast.
 
# PROJECT INFORMATION (ProjectInfoProperties)
spring.info.build.location=classpath:META-INF/build-info.properties # Location of the generated build-info.properties file.
spring.info.git.location=classpath:git.properties # Location of the generated git.properties file.
 
# JMX
spring.jmx.default-domain= # JMX domain name.
spring.jmx.enabled=true # Expose management beans to the JMX domain.
spring.jmx.server=mbeanServer # MBeanServer bean name.
 
# Email (MailProperties)
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
spring.mail.host= # SMTP server host. For instance `smtp.example.com`
spring.mail.jndi-name= # Session JNDI name. When set, takes precedence to others mail settings.
spring.mail.password= # Login password of the SMTP server.
spring.mail.port= # SMTP server port.
spring.mail.properties.*= # Additional JavaMail session properties.
spring.mail.protocol=smtp # Protocol used by the SMTP server.
spring.mail.test-connection=false # Test that the mail server is available on startup.
spring.mail.username= # Login user of the SMTP server.
 
# APPLICATION SETTINGS (SpringApplication)
spring.main.banner-mode=console # Mode used to display the banner when the application runs.
spring.main.sources= # Sources (class name, package name or XML resource location) to include in the ApplicationContext.
spring.main.web-environment= # Run the application in a web environment (auto-detected by default).
 
# FILE ENCODING (FileEncodingApplicationListener)
spring.mandatory-file-encoding= # Expected character encoding the application must use.
 
# INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.
 
# OUTPUT
spring.output.ansi.enabled=detect # Configure the ANSI output.
 
# PID FILE (ApplicationPidFileWriter)
spring.pid.fail-on-write-error= # Fail if ApplicationPidFileWriter is used but it cannot write the PID file.
spring.pid.file= # Location of the PID file to write (if ApplicationPidFileWriter is used).
 
# PROFILES
spring.profiles.active= # Comma-separated list (or list if using YAML) of active profiles.
spring.pro
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值