一.環(huán)境搭建
創(chuàng)建Maven項目
- 一般pom.xml會出錯,本地若無相應(yīng)版本的jar包,則無法下載或下載速度非常慢,我的解決方案是,查找本地倉庫的jar,修改為本地倉庫有的jar即可
- pom.xml的依賴jar可以從Maven搜索
二.Spring的 IOC(控制反轉(zhuǎn))與DI(依賴注入)
IOC(把Bean 的創(chuàng)建與管理交給Spring容器)
- 使用@Component,@Service,@Controller@Repository 注解Bean ,讓spring管理,四個功能等效,但應(yīng)該在相對應(yīng)的組件上標(biāo)識
- @Bean方式,在配置類中(有@Configuration注解的類) 用@bean注解的方法的返回值類型的Bean會被spring管理
DI 注入相應(yīng)的Bean
- @Autowired,@Inject, @Resource,可以注解在屬性或者Set方法上(我一般注解在屬性上,這樣可以省去set方法)
三.配置類的注解
- @Configuration標(biāo)識該類為配置類
- @ComponentScan(“包名”)讓spring掃描該包下的被注解為Bean的類
四.AOP(切面編程,基于cglib動態(tài)代理或者JDK動態(tài)代理)
- @Aspect標(biāo)注類為切面類
- @PoinCut(“execution(* com.aop.serivce.(..))”) 定義切點,被注解的方法名為切點名稱
- @Before前置通知,被標(biāo)注的方法會在目標(biāo)方法前執(zhí)行
- @After后置通知,被注解的方法會在目標(biāo)方法執(zhí)行過執(zhí)行
- @AfterReturning返回通知,在目標(biāo)方法執(zhí)行后切沒有異常時執(zhí)行
- @AfterThrowing 異常通知,在目標(biāo)方法執(zhí)行拋異常時執(zhí)行
- 使用時要在配置類上注解@EnableAspectJAutoProxy,開啟spring對AspectJ 的支持
五.常用配置
@Scope常用 有兩種取值 Singleton 和 Prototype
- Singleton 為默認(rèn)值 Bean我單例
- Prototype Bean為多例
配置文件讀取
- 在配置類上注解@ProperSource(“文件路徑”)
- 用@Value(“${key}”)注入配置文件的值
Bean的初始化和銷毀
- @PostConstruct 注解的方法會在Bean的構(gòu)造方法執(zhí)行后執(zhí)行
- @PreDestroy 注解的方法會在Bean銷毀前執(zhí)行
- @profile(“參數(shù)值”)注解Bean,可更具@ActiveProfiles(“參數(shù)值”)的參數(shù)值創(chuàng)建相應(yīng)的Bean
六.多線程
- 使用@EnableAsync 注解配置類開啟對異步任務(wù)的支持,
- 并且要實現(xiàn)AsyncConfiguer接口
- 創(chuàng)建一個線程池
- 在方法上注解@Async 就說明這個方法為異步方法
@Configuration
@ComponentScan("com.sjx.spring2.multithread")
@EnableAsync//開啟異步支持
public class TaskExecutorConfig implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
七.計劃任務(wù)
- 在配置類添加注解@EnableSchedule 開啟對計劃任務(wù)的支持
- 在方法上注解@Scheduled申明方法為計劃方法
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("當(dāng)前時間為"+dateFormat.format(new Date()));
}
@Scheduled(cron="0 17 10 ? * *")//每天的10點17
public void fixTimeExecution() {
System.out.println("當(dāng)定時時間"+dateFormat.format(new Date())+"執(zhí)行");
}
八.集成Junit
- @RunWith(SpringJUnit4ClassRunner.class)提供spring測試的上下文環(huán)境
- @Test標(biāo)識方法為測試方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AwareConfig.class})
public class AwareTest {
@Autowired
private AwareService service;
@Test
public void test1(){
service.outputResult();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。