SpringBoot 个人笔记-基础理论知识-走向自动装配

简介

Spring Boot是一个简化Spring开发的框架。用来监护spring应用开发,约定大于配置,去繁就简!!

我们在使用Spring Boot时只需要配置相应的Spring Boot就可以用所有的Spring组件,简单的说,spring boot就是整合了很多优秀的框架,不用我们自己手动的去写一堆xml配置然后进行配置。从本质上来说,Spring Boot就是Spring,它做了那些没有它你也会去做的Spring Bean配置。

1、SpringCloud依赖于SpringBoot框架

springBoot 是一个快速开发框架,能够快速整合第三方框架,简化xml配置,全部采用注解形式,内置web服务器,帮助开发者实现快速开发。springBoot web控制层框架默认集成springMVC。

SpringCloud是一套完善的微服务解决框架,在微服务领域通信协议http+Json格式,SpringCloud使用SpringMVC书写Http协议接口。(需要微服务才使用springCloud,否则仅使用SpringBoot就够了)

2、SpringBoot与SpringMvc的关系

SpringBoot中的web模块集成了SpringMVC框架。

3、maven 特性(聚合、继承、依赖管理)

通过继承parent,控制版本关系,依赖web模块,聚合需要的所有jar包

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- 整合所有相关的依赖jar包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 打包 :mvn celan  package
  • 跳过测试打包:mvn install -DskipTests   /   mvn install -Dmaven.test.skip=true
  • 运行:java –jar 包名    
  • 运行时指定端口:java -jar demo.jar --server.port=8066

4、热部署

原理:使用类加载器(classloader 重新读取字节码文件到jvm内存)
1.不推荐使用在生成环境。(部署的同时,玩家非常卡。容易出现数据异常)
2.使用在本地开发,提高开发效率。

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>true</scope>
		</dependency>

 这个也是热部署,在开发中使用

 

手动装配

模式注解装配(就是通过@Component等 注入bean)、模块装配、条件装配

 

模块装配

定义:具备相同领域的功能组件集合,组合所形成的一个独立单元。(@EnableWebMvc、@EnableAutoConfiguration)

通过注解直接传入bean

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldConfiguration.class)
public @interface EnableHelloWorld {
}
public class HelloWorldConfiguration {
 
    @Bean
    public String helloWorld() { // 方法名即 Bean 名称
        return "Hello,World 2018";
    }
 
}
@EnableHelloWorld
public class EnableHelloWorldBootstrap {
 
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
 
        // helloWorld Bean 是否存在
        String helloWorld =
                context.getBean("helloWorld", String.class);
 
        System.out.println("helloWorld Bean : " + helloWorld);
 
        // 关闭上下文
        context.close();
    }
}

Selector

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
//@Import(HelloWorldConfiguration.class)  这是注解驱动的方式
@Import(HelloWorldImportSelector.class)  //这个是接口编程的方式
public @interface EnableHelloWorld {
}
public class HelloWorldImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        System.out.println("selectTOr判断逻辑以及返回HelloWorldConfiguration");
        return new String[]{HelloWorldConfiguration.class.getName()};
    }
}

条件装配

定义:bean装配的前置判断(@Profile、@Conditional)

profile

public interface CalculateService {

    /**
     * 从多个整数 sum 求和
     * @param values 多个整数
     * @return sum 累加值
     */
    Integer sum(Integer... values);
}
@Profile("Java7")
@Service
public class Java7CalculateService implements CalculateService {
    @Override
    public Integer sum(Integer... values) {
        System.out.println("Java 7 for 循环实现 ");
        int sum = 0;
        for (int i = 0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
}
@Profile("Java8")
@Service
public class Java8CalculateService implements CalculateService {

    @Override
    public Integer sum(Integer... values) {
        System.out.println("Java 8 Lambda 实现");
        int sum = Stream.of(values).reduce(0, Integer::sum);
        return sum;
    }
}

 profile 可以在配置中添加

@SpringBootApplication
public class CalculateServiceBootstrap {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(CalculateServiceBootstrap.class)
                .web(WebApplicationType.NONE)
                .profiles("Java8")
                .run(args);

        // CalculateService Bean 是否存在
        CalculateService calculateService = context.getBean(CalculateService.class);
        System.out.println("calculateService.sum(1...10) : " + calculateService.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        // 关闭上下文
        context.close();
    }
}

Conditional  (根据条件判断注入bean)

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {

    /**
     * Java 系统属性名称
     * @return
     */
    String name();

    /**
     * Java 系统属性值
     * @return
     */
    String value();
}
public class OnSystemPropertyCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        String propertyName = String.valueOf(attributes.get("name"));
        String propertyValue = String.valueOf(attributes.get("value"));
        String javaPropertyValue = System.getProperty(propertyName);
        //作者和用户匹配
        return propertyValue.equals(javaPropertyValue);
    }
}
    @Bean
    @ConditionalOnSystemProperty(name = "user.name", value = "Admin")
    public String helloWorld() {
        return "Hello,World 小马哥";
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionalOnSystemPropertyBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        // 通过名称和类型获取 helloWorld Bean
        String helloWorld = context.getBean("helloWorld", String.class);

        System.out.println("helloWorld Bean : " + helloWorld);

        // 关闭上下文
        context.close();
    }

自动装配

定义:基于预定大于配置的原则,实现Spring组件自动装配的目的。

实现:

  • 激活自动装配:@EnableAutoConfigration
  • 实现自动装配:xxxAutoConfiguration
  • 配置自动装配实现:META-INF/spring.factories
@EnableAutoConfiguration
public class EnableAutoConfigurationBootstrap {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);

        // helloWorld Bean 是否存在
        String helloWorld =
                context.getBean("helloWorld", String.class);
        System.out.println("helloWorld Bean : " + helloWorld);
        // 关闭上下文
        context.close();
    }
}
@Configuration // Spring 模式注解装配
@EnableHelloWorld // Spring @Enable 模块装配
@ConditionalOnSystemProperty(name = "user.name", value = "Admin") // 条件装配
public class HelloWorldAutoConfiguration {
    
}

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.imooc.diveinspringboot.configuration.HelloWorldAutoConfiguration

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值