spring

重新安装idea 和gradle 搭建一个项目,此刻项目正在下载gradle 的相关包,spring boot的书重新拿出来翻翻,温故一下,加深一下记忆,现在公司要做后台接口项目,之前一直在看前端的东西。

看着文档看着看着,越来越感觉大家都有或多或少的想通之处,某些方面表现出来的东西也差不多,虽然风格不同,但作用或目的都有相似。

spring 推荐使用java 配置代替xml 配置。

bean 是spring 管理实例的单位,声明一个bean 以为着spring 会管理相关的类,理解为编译类的包装比较好理解。

声明注解:

@bean、@service、@repository、@controller

注入

@autowired、@inject、@resource、后面2个用的甚少。

声明配置类:node 也有配置,所有的框架或者插件需要有配置,很多也都有配置类的存在,bean更类似于一个实例,但不是实例

@Configuretion: 声明一个配置类(JAVA 配置)全局

@Bean:声明在一个方法上,声明此方法返回的是一个bean

通过构造函数直接注入,不使用antowired注入。

aop:面向切面

添加依赖

@AspectJ 声明切面

@After、@Before、@Around  生命周期

在声明周期中指定切点或切面,返回一个joinPoint 参数,通过此参数获取相关信息

@After("annotationPointCut()")
    public void after(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        System.out.println(method.getName());
    }

    @Before("execution(* com.duoke.demo.service.MethodService.*(..))")
    public void before(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        System.out.println(method.getName());
    }

作用域:bean 个数

1.Singleton :默认,单例

2.Prototype:每次新建一个新的实例

3.request:每次http request调用新建

4.session:http session 新建一个实例

5.protal项目新建实例(protal 不明)

@Scope   类声明scope

spring el表达式:资源调用依赖common-io

获取配置文件中的数据

@PropertySource(value = "classpath:application.properties")
 @Value("${author.name}")
    private String name;

bean声明周期:创建和销毁

init 方法和destroy 方法,在初始化时调用,且在调用构造函数之后和实际销毁之前执行。

@Bean(initMethod="",destoryMethod="")

Profile: 有点类似条件编译的意思

注册环境状态(springboot 直接在总配置文件中直接可配置)

configApplicationContext.getEnvironment().setActiveProfiles("dev");

在spring上下文中获取的bean 会根据profile的激活状态返回不同的实例

@Profile("dev")
    @Bean(initMethod = "init")
    public ProfileBean dev(){
        return  new ProfileBean("dev");
    }

    @Profile("prod")
    @Bean
    public ProfileBean pro(){
        return new ProfileBean("prod");
    }

Bean之间的消息通信:事件监听、事件发送 applicationEvent

监听

@Component
public class CustomListener implements ApplicationListener<CustomEvent> {
    @Override
    public void onApplicationEvent(CustomEvent event) {
        String msg = event.getMsg();
        System.out.println("THIS MSG FROM CUSTOMEVENT"+msg);
    }
}

自定义事件

public class CustomEvent extends ApplicationEvent {

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public CustomEvent(Object source,String msg) {
        super(source);
        this.msg = msg;
    }

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

触发事件

@Component
public class CustomPublish {
    @Autowired
//            注入应用监听上下文
            ApplicationContext context;

    //    发送事件
    public void publish(String msg) {
        context.publishEvent(new CustomEvent(this,"this is from publish"));
    }
}

多线程:TaskExecutor(jdk 提供的Executor的子集)

@EnableAsync 开启异步任务支持

@Async 声明异步任务

使用ThreadPoolTaskExecutor,通过executor 执行异步任务,比较方便,但是有时候直接使用jdk提供的情况可能会较多。

计划任务:scheduledTaskService

@EnableScheduling 开启计划任务

@Scheduled : 计划任务声明

@Configuration
@ComponentScan(value = "com.duoke.demo.job")
@EnableScheduling
public class JobConfig {

}

条件注解:Condition

@Conditional 根据满足的某一个特定条件创建一个Bean

 @Bean
    @Conditional(value = WinCondition.class)
    public CmdService isWin(){
        return new WindowOsBean();
    }
// 判断当前环境
public class WinCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Boolean isWin = context.getEnvironment().getProperty("os.name").contains("Windows");
        Map<String, Object> name = metadata.getAnnotationAttributes("");

        return isWin;
    }
}

组合注解、元注解(标记在注解上的)

// /** Class, interface (including annotation type), or enum declaration */
@Target(ElementType.TYPE)
// 保存政策:运行时
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface CustomAnno {
    String value() default "This is CustomAnno";
}

@Enable* 注解开启功能原理

使用@Import 注解导入配置。(其中有一些是条件判断引入)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {

spring 测试支持:

集成junit、testNg,@RunWith 指定测试框架、@ContextConfiguration 指定测试配置

就跟一个普通的bean 一样,注入需要测试bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("prod")
public class SpringTest {
    @Autowired
    private TestBean testBean;

    @Test
    public void test(){
        System.out.println(testBean.getContext());
    }
原文地址:https://www.cnblogs.com/jony-it/p/11348722.html