1、Spring Aware(获取Spring容器的服务)

hi, i am guodaxia!

test.txt

package com.zhen.highlights_spring4.ch3.aware;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service; import java.io.IOException; /**
* @author zhen
* @Date 2018/7/2 10:49
*/
@Service("awareService")
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader resourceLoader; @Override
public void setBeanName(String beanName) {
this.beanName = beanName;
} @Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
} public void outputResult(){
System.out.println("Bean的名称为:" + beanName);
Resource resource = resourceLoader.getResource("classpath:/com/zhen/highlights_spring4/ch3/aware/test.txt");
try{
System.out.println("ResourceLoader加载的文件内容为:" + IOUtils.toString(resource.getInputStream()));
}catch (IOException e){
e.printStackTrace();
}
}
}
package com.zhen.highlights_spring4.ch3.aware; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; /**
* @author zhen
* @Date 2018/7/2 10:53
*/
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch3.aware")
public class AwareConfig {
}
package com.zhen.highlights_spring4.ch3.aware; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* @author zhen
* @Date 2018/7/2 10:54
*/
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult(); context.close();
}
}

2、多线程

package com.zhen.highlights_spring4.ch3.taskexecutor;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; /**
* @author zhen
* @Date 2018/7/2 11:02
*/
@Service
public class AsyncTaskService { @Async
public void executeAsyncTask(Integer i){
System.out.println("执行异步任务:" + i);
} @Async
public void executeAsyncTaskPlus(Integer i){
System.out.println("执行异步任务+1:" + (i+));
}
}
package com.zhen.highlights_spring4.ch3.taskexecutor; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /**
* @author zhen
* @Date 2018/7/2 10:57
*/
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch3.taskexecutor")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer { @Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExcutor = new ThreadPoolTaskExecutor();
taskExcutor.setCorePoolSize();
taskExcutor.setMaxPoolSize();
taskExcutor.setQueueCapacity();
taskExcutor.initialize();
return taskExcutor;
} @Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
package com.zhen.highlights_spring4.ch3.taskexecutor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* @author zhen
* @Date 2018/7/2 11:05
*/
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class); AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class); for(int i=; i<; i++){
asyncTaskService.executeAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
} context.close();
}
}

3、计划任务

package com.zhen.highlights_spring4.ch3.taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import java.text.SimpleDateFormat;
import java.util.Date; /**
* @author zhen
* @Date 2018/7/2 14:59
*/
@Service
public class ScheduledTaskService { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = )
public void reportCurrentTime(){
System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date()));
} @Scheduled(cron = "0 16 15 ? * *")
public void fixTimeExcution(){
System.out.println("在指定时间 " + dateFormat.format(new Date()) + "执行");
}
}
package com.zhen.highlights_spring4.ch3.taskscheduler; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling; /**
* @author zhen
* @Date 2018/7/2 15:09
*/
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch3.taskscheduler")
@EnableScheduling
public class TaskSchedualerConfig {
}
package com.zhen.highlights_spring4.ch3.taskscheduler; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* @author zhen
* @Date 2018/7/2 15:10
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedualerConfig.class);
}
}

4、条件注解

package com.zhen.highlights_spring4.ch3.conditional;

/**
* @author zhen
* @Date 2018/7/2 15:32
*/
public interface ListService {
public String showListCmd();
}
package com.zhen.highlights_spring4.ch3.conditional; /**
* @author zhen
* @Date 2018/7/2 15:32
*/
public class WindowsListService implements ListService {
@Override
public String showListCmd() {
return "dir";
}
}
package com.zhen.highlights_spring4.ch3.conditional; /**
* @author zhen
* @Date 2018/7/2 15:33
*/
public class LinuxListService implements ListService {
@Override
public String showListCmd() {
return "ls";
}
}
package com.zhen.highlights_spring4.ch3.conditional; import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; /**
* @author zhen
* @Date 2018/7/2 15:21
*/
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("os.name").contains("Windows");
}
}
package com.zhen.highlights_spring4.ch3.conditional; import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata; /**
* @author zhen
* @Date 2018/7/2 15:21
*/
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return conditionContext.getEnvironment().getProperty("os.name").contains("Linux");
}
}
package com.zhen.highlights_spring4.ch3.conditional; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; /**
* @author zhen
* @Date 2018/7/2 15:33
*/
@Configuration
public class ConditionConfig { @Bean
@Conditional(WindowsCondition.class)
public ListService windowsListService(){
return new WindowsListService();
} @Bean
@Conditional(LinuxCondition.class)
public ListService linuxListService(){
return new LinuxListService();
}
}
package com.zhen.highlights_spring4.ch3.conditional; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author zhen
* @Date 2018/7/2 15:40
*/
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
ListService listService = context.getBean(ListService.class);
System.out.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令为: " + listService.showListCmd()); context.close();
}
}

5、组合注解

package com.zhen.highlights_spring4.ch3.annotation;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import java.lang.annotation.*; /**
* @author zhen
* @Date 2018/7/2 15:48
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface WiselyConfiguration {
String[] value() default {};
}
package com.zhen.highlights_spring4.ch3.annotation; /**
* @author zhen
* @Date 2018/7/2 16:00
*/
@WiselyConfiguration("com.zhen.highlights_spring4.ch3.annotation")
public class DemoConfig {
}
package com.zhen.highlights_spring4.ch3.annotation; import org.springframework.stereotype.Service; /**
* @author zhen
* @Date 2018/7/2 15:53
*/
@Service
public class DemoService { public void outputResult(){
System.out.println("从组合注解配置照样获得的bean");
}
} package com.zhen.highlights_spring4.ch3.annotation; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* @author zhen
* @Date 2018/7/2 16:01
*/
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();
}
}

6、测试

package com.zhen.highlights_spring4.ch3.fortest;

/**
* @author zhen
* @Date 2018/7/2 16:04
*/
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;
}
}
package com.zhen.highlights_spring4.ch3.fortest; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; /**
* @author zhen
* @Date 2018/7/2 16:05
*/
@Configuration
public class TestConfig { @Bean
@Profile("dev")
public TestBean devTestBean(){
return new TestBean("from development profile");
} @Bean
@Profile("prod")
public TestBean prodTestBean(){
return new TestBean("from production profile");
}
}
package com.zhen.highlights_spring4.ch3.fortest; import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /**
* @author zhen
* @Date 2018/7/2 16:30
*/ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("prod")
public class DemoBeanIntegrationTests { @Autowired
private TestBean testBean; @Test
public void prodBeanShouldInject(){
String expected = "from production profile";
String actual = testBean.getContent();
Assert.assertEquals(expected, actual);
}
}

springboot学习章节代码-spring高级话题的更多相关文章

  1. springboot学习章节代码-Spring MVC基础

    1.项目搭建. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  2. springboot学习章节代码-spring基础

    1.DI package com.zhen.highlights_spring4.ch1.di; import org.springframework.stereotype.Service; /** ...

  3. Spring高级话题-@Enable***注解的工作原理

    出自:http://blog.csdn.net/qq_26525215 @EnableAspectJAutoProxy @EnableAspectJAutoProxy注解 激活Aspect自动代理 & ...

  4. springboot学习章节-spring常用配置

    1.Scope package com.zhen.highlights_spring4.ch2.scope; import org.springframework.context.annotation ...

  5. Spring Boot实战笔记(九)-- Spring高级话题(组合注解与元注解)

    一.组合注解与元注解 从Spring 2开始,为了响应JDK 1.5推出的注解功能,Spring开始大量加入注解来替代xml配置.Spring的注解主要用来配置注入Bean,切面相关配置(@Trans ...

  6. springboot学习之授权Spring Security

    SpringSecurity核心功能:认证.授权.攻击防护(防止伪造身份) 涉及的依赖如下: <dependency> <groupId>org.springframework ...

  7. Spring Boot实战(3) Spring高级话题

    1. Spring Aware Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的.即你可以将你的容器替换成别的容器. 实际项目中,不可避免地会用到Spring容 ...

  8. SpringBoot学习笔记:Spring Data Jpa的使用

    更多请关注公众号 Spring Data Jpa 简介 JPA JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR ...

  9. Spring Boot实战笔记(八)-- Spring高级话题(条件注解@Conditional)

    一.条件注解@Conditional 在之前的学习中,通过活动的profile,我们可以获得不同的Bean.Spring4提供了一个更通用的基于条件的Bean的创建,即使用@Conditional注解 ...

随机推荐

  1. 初步了解hg19注释文件的内容 | gtf

    hg19有哪些染色体? chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 c ...

  2. 2017-2018-2 20165327 实验三《敏捷开发与XP实践》实验报告

    2017-2018-2 20165327 实验三<敏捷开发与XP实践>实验报告 实验三 <敏捷开发与XP实践> 一.实验报告封面 课程:Java程序设计 班级:1653 姓名: ...

  3. WPF:数据和行为

    如果自己来做一个UI框架,我们会首先关注哪些方面?我想UI框架主要处理的一定包括两个主要层次的内容,一个是数据展现,另一个就是数据操作,所以UI框架必须能够接收各种不同的数据并通过UI界面展现出来,然 ...

  4. 微信小程序如何导入字体图标

    前提:我们已经拥有了从阿里图标库下载下来的一系列的字体图标文件1:找个其中的ttf格式的文件,然后打开https://transfonter.org/网站2:点击Add fonts按钮,加载ttf格式 ...

  5. hdu-6194 string string string 后缀数组 出现恰好K次的串的数量

    最少出现K次我们可以用Height数组的lcp来得出,而恰好出现K次,我们只要除去最少出现K+1次的lcp即可. #include <cstdio> #include <cstrin ...

  6. 【洛谷p1164】小A点菜

    (……) 小A点菜[传送门] 上标签: (一个神奇的求背包问题方案总数的题) 核心算法: ;i<=n;i++) for(int j=m;j>=a[i];j--) f[j]+=f[j-a[i ...

  7. jquery快速获得url 的get传值

    <script> var res = location.search.substr(1).split("&"); var arr={}; for (var i ...

  8. Pudding Monsters CodeForces - 526F (分治, 双指针)

    大意: n*n棋盘, n个点有怪兽, 求有多少边长为k的正方形内恰好有k只怪兽, 输出k=1,...,n时的答案和. 等价于给定n排列, 对于任意一个长为$k$的区间, 若最大值最小值的差恰好为k, ...

  9. AS(Android Studio)不停的updating indices

    有同事问我他as进入后updating iindices个不停 就在此处一直刷一直刷,虽然对他项目没什么影响,但总归很是烦人,解决办法如下: 打开File->Invalidate Caches ...

  10. 一、JAVA内存区域与内存溢出异常

    在虚拟机自动内存管理机制的帮助下,不在需要为每一个操作区写相对应的delete/free代码来进行内存释放.进而不容易出现内存泄露和内存溢出的问题,由虚拟机管理内存,貌似这一切看起来很好.也正是因为j ...