第3章 Spring 高级话题

2018-12-05  本文已影响0人  意大利大炮

Spring Aware

接口 用途/说明
BeanNameAware 可以在Bean中得到它在IOC容器中的Bean的实例的名字
BeanFactoryAware 可以在Bean中得到Bean所在的IOC容器,从而直接在Bean中使用IOC容器的服务
ApplicationContextAware 可以在Bean中得到Bean所在的应用上下文,从而直接在Bean中使用上下文的服务
MessageSourceAware 在Bean中可以得到消息源
ApplicationEventPublisherAware 在bean中可以得到应用上下文的事件发布器,从而可以在Bean中发布应用上下文的事件
ResourceLoaderAware 在Bean中可以得到ResourceLoader,从而在bean中使用ResourceLoader加载外部对应的Resource资源
@Service
public class AwareService implements ResourceLoaderAware{
  @Override
  public void setResourceLoader(ResourceLoader resourceLoader) {
    this.loader = resourceLoader;
  }
}

多线程

下面是一个例子

@Configuration
@ComponentScan("com.example.demo")
@EnableAsync                            //  使用注解开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
@Service
public class AsyncTaskService {

    @Async
    public void executeAsyncTask(Integer i) {
        System.out.println("执行异步任务1:" + i);
    }

    @Async
    public void executeAsyncTaskPlus(Integer i) {
        System.out.println("执行异步任务2:" + i);
    }
}
public class Main {
    public static void main(String args[]) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(TaskExecutorConfig.class);

        AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
        // 循环调用
        for (int i = 0; i < 10; i++) {
            asyncTaskService.executeAsyncTask(i);
            asyncTaskService.executeAsyncTaskPlus(i);
        }
        // 关闭
        context.close();
    }
}

计划任务(定时任务)

@Configuration
@ComponentScan("com.example.demo.scheduled_test.service")
@EnableScheduling               // 开启定时任务的支持
public class TaskSchedulerConfig {
}
@Service
public class ScheduledTaskService {

    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTime() {
        System.out.println("每个五秒钟执行一次 ");
    }
    /**
     * 在每天的11点28分执行
     */
    @Scheduled(cron = "0 28 11 ? * *")
    public void fixTimeExecution() {
        System.out.println("在指定时间执行");
    }
}
public class Main {
    public static void main(String args[]) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);

    }
}

条件注解@Conditional

public class WindowsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return conditionContext.getEnvironment().getProperty("os.name").contains("Windows");
    }
}

linux定义

public class LinuxCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return conditionContext.getEnvironment().getProperty("os.name").contains("Linux");
    }
}
public interface ListService {
    String showListCmd();
}

windows下要创建的Bean

public class WindowsListService implements ListService {
    @Override
    public String showListCmd() {
        return "dir";
    }
}

Linux下要创建的Bean

public class LinuxListService implements ListService {
    @Override
    public String showListCmd() {
        return "ls";
    }
}
@Configuration
public class ConditionConfig {

    @Bean
    @Conditional(WindowsCondition.class)
    public ListService windows() {
        return new WindowsListService();
    }
    @Bean
    @Conditional(LinuxCondition.class)
    public ListService linux() {
        return new LinuxListService();
    }
}
public class Main {
    public static void main(String args[]) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);

        ListService listService = context.getBean(ListService.class);

        System.out.println("列表命令: " + listService.showListCmd());
    }
}

组合注解与元注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface WiselyConfiguration {
    String[] value() default {};
}
@Service
public class DemoService {
    public void outPutResult() {
        System.out.println("从组合注解处照样获得的bean");
    }
}
@WiselyConfiguration("com.example.demo.simple_conditional.service")
public class DemoConfig {
}
public class Main {
    public static void main(String args[]) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
        DemoService demoService = context.getBean(DemoService.class);
        demoService.outPutResult();
    }
}

@Enable* 注解的工作原理

  1. 直接导入配置类
  2. 依据条件选择配置类
  3. 动态注册Bean

测试

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>apring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
public class TestBean {

    private String content;

    public TestBean(String content) {
        super();
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
@Configuration
public class TestConfig {

    @Bean
    @Profile("dev")
    public TestBean devTestBean() {
        return new TestBean("dev");
    }

    @Bean
    @Profile("prod")
    public TestBean prodTestBean() {
        return new TestBean("prod");
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestBean.class})
@ActiveProfiles("prod")
public class Main {
    @Autowired
    private TestBean testBean;

    @Test
    public void test() {
        System.out.println(testBean.getContent());
    }
}
上一篇下一篇

猜你喜欢

热点阅读