Spring高级配置

18 篇文章 0 订阅
10 篇文章 0 订阅

Spring Aware

spring aware提供的接口:

 

BeanNameAware获得容器Bean的名称
BeanFactoryAware获取容器的Bean Factory,获取容器的服务
ApplicationContextAware当前的Application Aware,可以调用同期的服务
MessageSourceAware获取message source,这样可以获取文本信息
ApplicationEventPublisherAware应用时间发布器,可以发布事件
ResourceLoaderAware获得资源加载器,可以获取外部资源
import java.io.IOException;

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;

@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {

	private String beanName;
	private ResourceLoader loader;

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.loader = resourceLoader;
	}

	@Override
	public void setBeanName(String name) {
		this.beanName = name;
	}

	public void outputResult() {
		System.out.println("Bean的名称为: " + beanName);
		Resource resource = loader.getResource("classpath:text.txt");
		try {
			System.out.println("解析的文内容件: " + IOUtils.toString(resource.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.fish.ch3.aware")
public class AwareConfig {
	
}

多线程

Spring通过TaskExecutor来实现多线程和并发编程,使用ThradPoolTaskExecutor可实现一个基于线程池TaskExecutor。在配置类中通过@EnableAsync开启对异步的支持。并通过在实际执行的Bean的方法中使用@Async注解声明其实一个异步任务。

@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 + 1));
	}
}
@Configuration
@ComponentScan("com.fish.ch3.taskexecutor")
@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;
	}

}

计划任务

通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在执行计划任务的方法上使用注解@Scheduled支持多种类型的计划任务,包括cron,fixDelay,fixRate。

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
@ComponentScan("com.fish.ch3.scheduled")
public class TaskSchedulerConfig {

}
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledTaskService {
	private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
	
	@Scheduled(fixedDelay=6000)
	public void reportCurrentTime() {
		System.out.println("每6秒执行一次" +dataFormat.format(new Date()) );
	}
	
	@Scheduled(cron="0 35 17 ? * * ")
	public void cronExecution() {
		System.out.println("制定的时间");
	}
	
	@Scheduled(fixedRate = 7000)
	public void fixRate() {
		System.out.println("每7秒执行一次 *******");
	}
}

条件注解@Conditional

通过profile我们可以获得不同的Bean。Spring4.x提供了更通用额基于条件的bean的创建。即使用@Conditional注解。@Conditional根据满足某一个特定的条件创建Bean。

组合注解和元注解

元注解就是可以注解在其他注解上的注解,被注解的注解称之为组合注解。

@Enable*注解的工作原理

  1. @EnableAspectJAutoProxy开启对AspectJ自动代理的支持。
  2. @EnableAsync开启异步方法的支持
  3. @EnableScheduling开启计划任务的支持
  4. @EnableWebMvc开启WebMVC的配置支持
  5. @EnableConfigurationProperties开启对@COnfigurationProperties的注解配置Bean的支持。
  6. @EnableJpaRepostitories开启对Spring Data JPA Repository的支持
  7. @EnableTransactionManagement开启注解式事务的支持。
  8. @EnableCaching开启注解式的缓存支持。

测试

Spring 通过 Spring  TestContextFrameword对集成测试提供顶级支持。

Spring提供了一个SpringJUnit4ClassRunner类,他提供了Spring TestContext Framework的功能。通过@ContextConfiguration来配置Application Context,通过@ActiveProfiles确认活动的profile。

package com.fish.ch3.test;

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("form development profile");
    }

    @Bean
    @Profile("prod")
    public TestBean proTestBean() {
        return new TestBean("from production profile");
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {TestConfig.class })
@ActiveProfiles("dev")
public class DemoBeanIntegrationTests {

	@Autowired
	private TestBean testBean;
	
	@Test
	public void devBean() {
		String expected = "form development profile";
		String actual = testBean.getContent();
		Assert.assertEquals(expected, actual);
	}
	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值