Spring Advanced Topics (2)

Source: Internet
Author: User
Tags dateformat

Directory

    • 1. Scheduled Tasks @scheduled
      • 1.1. Theory
      • 1.2. Example
    • 2. Conditional Annotations @conditional
      • 2.1. Theory
      • 2.1. Example
    • 3. Combination annotations and meta annotations
      • 3.1. Theory
      • 3.2. Example

All code samples must be configured to quickly build the spring Spring project.
This series is to give back learning Springboot lay a good foundation, so the purpose of this series is not to explain the knowledge of spring, but the work of the common knowledge points listed out, because Springboot with the Java configuration, so in the list of knowledge points when all the Java configuration.

1, the planning task @scheduled1.1, theory

The implementation of the scheduled task in spring will become very simple, using @enablescheduling directly on the configuration class to turn on support for the scheduled task, and then annotate @scheduled on the method to perform the scheduled task, declaring that this is a scheduled task. For example @Scheduled(cron = "0 0 6 * * ?") , to start the task every morning at six, where the corn expression can be Baidu.

1.2. Example

1) Configuration Class

package com.wisely.highlight_spring4.ch3.taskscheduler;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;@Configuration//表示这是一个配置类//会自动扫描在这个地址下面的所有的包及其他们的子包@ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")@EnableScheduling //开启计划任务支持public class TaskSchedulerConfig {}

2) Execution class

package com.wisely.highlight_spring4.ch3.taskscheduler;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;@Servicepublic class ScheduledTaskService {          private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");      @Scheduled(cron = "*/5 * * * * ?"  ) //每隔5秒执行一次      public void fixTimeExecution(){          System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");      }}

3) Test class

package com.wisely.highlight_spring4.ch3.taskscheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {         AnnotationConfigApplicationContext context =                    new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);             }}

4) Results

2, the condition annotation @conditional2.1, the theory

We've said before that we can get different bean,spring4 by profile. Provides a more generic condition-based bean creation---use @conditional annotations. In fact, it is based on the conditions to determine which implementation class to assemble. Springboot will apply a lot of conditional annotations, let's look at an example first.

2.1. Example

1) Create a service interface class

package com.wisely.highlight_spring4.ch3.conditional;public interface ListService {    public String showListCmd();}

2) Interface Implementation class

package com.wisely.highlight_spring4.ch3.conditional;public class WindowsListService implements ListService {    @Override    public String showListCmd() {        return "dir";    }}
package com.wisely.highlight_spring4.ch3.conditional;public class LinuxListService implements ListService{    @Override    public String showListCmd() {        return "ls";    }}

3) Condition Judgment class

  package Com.wisely.highlight_spring4.ch3.conditional;import Org.springframework.context.annotation.condition;import Org.springframework.context.annotation.ConditionContext    ; Import Org.springframework.core.type.annotatedtypemetadata;public class Windowscondition implements Condition { Public Boolean matches (Conditioncontext context, Annotatedtypemetadata metadata) {return context.getenv    Ironment (). GetProperty ("Os.name"). Contains ("Windows"); }}
package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.Condition;import org.springframework.context.annotation.ConditionContext;import org.springframework.core.type.AnnotatedTypeMetadata;public class LinuxCondition implements Condition {    public boolean matches(ConditionContext context,            AnnotatedTypeMetadata metadata) {        return context.getEnvironment().getProperty("os.name").contains("Linux");    }}

4) Configuration Class

package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Conditional;import org.springframework.context.annotation.Configuration;@Configurationpublic class ConditionConifg {    @Bean    @Conditional(WindowsCondition.class) //如果WindowsCondotion类返回的是true则实例化WindowsListService    public ListService windowsListService() {        return new WindowsListService();    }    @Bean    @Conditional(LinuxCondition.class) //如果LinuxCondition类返回的是true则实例化LinuxListService    public ListService linuxListService() {        return new LinuxListService();    }}

5) Test class

package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context =                new AnnotationConfigApplicationContext(ConditionConifg.class);                ListService listService = context.getBean(ListService.class);                        System.out.println(context.getEnvironment().getProperty("os.name")                 + "系统下的列表命令是: "                 + listService.showListCmd());                context.close();    }}

6) Results

3. Combination annotations and meta-annotations 3.1, theory
    • Combination annotations: It is the combination of multiple annotations into a new annotation.
    • Meta-Annotations: Annotations that modify annotations (@Target, @Retention, @Documented, @Inherited).
3.2. Example

The main demonstration of the combination of annotations
1) configuration combination annotations

package com.wisely.highlight_spring4.ch3.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Configuration @ComponentScan public @interface ABC {        String[] value() default {}; }

2) New Configuration class

package com.wisely.highlight_spring4.ch3.annotation;@ABC("com.wisely.highlight_spring4.ch3.annotation")public class DemoConfig {}

3) Service Bean

package com.wisely.highlight_spring4.ch3.annotation;import org.springframework.stereotype.Service;@Servicepublic class DemoService {        public void outputResult(){        System.out.println("新注解获取Bean");    }}

4) Testing

package com.wisely.highlight_spring4.ch3.annotation;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {        public static void main(String[] args) {        AnnotationConfigApplicationContext context =                new AnnotationConfigApplicationContext(DemoConfig.class);                DemoService demoService =  context.getBean(DemoService.class);                demoService.outputResult();                context.close();    }}

5) Results

Spring Advanced Topics (2)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.