1.pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wisely</groupId>
<artifactId>highlight_spring4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.7</java.version>
<spring-framework.version>4.1.5.RELEASE</spring-framework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- spring aop支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- aspectj支持 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<!-- Spring test 支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
AOP
- 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name();
}
使用注解
@Service
public class DemoAnnotationService {
@Action(name="注解式拦截的add操作")
public void add(){}
}
方法
@Service
public class DemoMethodService {
public void add(){}
}
- 切面
@Aspect //1
@Component //2
public class LogAspect {
@Pointcut("@annotation(com.wisely.highlight_spring4.ch1.aop.Action)") //3
public void annotationPointCut(){};
@After("annotationPointCut()") //4
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("注解式拦截 " + action.name()); //5
}
@Before("execution(* com.wisely.highlight_spring4.ch1.aop.DemoMethodService.*(..))") //6
public void before(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("方法规则式拦截,"+method.getName());
}
}
- 配置
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch1.aop")
@EnableAspectJAutoProxy //1
public class AopConfig {
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AopConfig.class); //1
DemoAnnotationService demoAnnotationService = context.getBean(DemoAnnotationService.class);
DemoMethodService demoMethodService = context.getBean(DemoMethodService.class);
demoAnnotationService.add();
demoMethodService.add();
context.close();
}
DI
@Configuration //1
@ComponentScan("com.wisely.highlight_spring4.ch1.di") //2
public class DiConfig {
}
@Service //1
public class FunctionService {
public String sayHello(String word){
return "Hello " + word +" !";
}
}
@Service //1
public class UseFunctionService {
@Autowired //2
FunctionService functionService;
public String SayHello(String word){
return functionService.sayHello(word);
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(DiConfig.class); //1
UseFunctionService useFunctionService = context.getBean(UseFunctionService.class); //2
System.out.println(useFunctionService.SayHello("world"));
context.close();
}
javaconfig
public class FunctionService {
public String sayHello(String word){
return "Hello " + word +" !";
}
}
public class UseFunctionService {
//2
FunctionService functionService;
public void setFunctionService(FunctionService functionService) {
this.functionService = functionService;
}
public String SayHello(String word){
return functionService.sayHello(word);
}
}
@Configuration //1
public class JavaConfig {
@Bean //2
public FunctionService functionService(){
return new FunctionService();
}
@Bean
public UseFunctionService useFunctionService(){
UseFunctionService useFunctionService = new UseFunctionService();
useFunctionService.setFunctionService(functionService()); //3
return useFunctionService;
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(JavaConfig.class);
UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);
System.out.println(useFunctionService.SayHello("java config"));
context.close();
}
scope
@Service
@Scope("prototype")//1
public class DemoPrototypeService {
}
@Service //1
public class DemoSingletonService {
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.scope")
public class ScopeConfig {
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ScopeConfig.class);
DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
System.out.println("s1与s2是否相等:"+s1.equals(s2));
System.out.println("p1与p2是否相等:"+p1.equals(p2));
context.close();
}
prototype
singleton 默认
request 给每个http request新建一个实例
session 给每个http session新建一个实例
globalsession 只在portal应用有用, 给每个global http session 新建一个实例
Spring El
@Service //get set
public class DemoService {
@Value("其他类的属性") //1
private String another;
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.el")
//@PropertySource("classpath:/com/wisely/highlight_spring4/ch2/el/test.properties")//7
@PropertySource("classpath:test.properties") //最好还是这样访问
public class ElConfig {
@Value("I Love You!") //1
private String normal;
@Value("#{systemProperties['os.name']}") //2
private String osName;
@Value("#{ T(java.lang.Math).random() * 100.0 }") //3
private double randomNumber;
@Value("#{demoService.another}") //4
private String fromAnother;
/*@Value("classpath:com/wisely/highlight_spring4/ch2/el/test.txt") //5*/
@Value("classpath:test.txt")
private Resource testFile;
@Value("http://www.baidu.com") //6
private Resource testUrl;
@Value("${book.name}") //7
private String bookName;
@Autowired
private Environment environment; //7
@Bean //7
public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
return new PropertySourcesPlaceholderConfigurer();
}
public void outputResource() {
try {
System.out.println(normal);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(fromAnother);
System.out.println(IOUtils.toString(testFile.getInputStream()));
System.out.println(IOUtils.toString(testUrl.getInputStream()));
System.out.println(bookName);
System.out.println(environment.getProperty("book.author"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
test.properties
book.author=wangyunfeidalao
book.name=spring boot
test.txt 文字随便
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ElConfig.class);
ElConfig resourceService = context.getBean(ElConfig.class);
resourceService.outputResource();
context.close();
}
bean的初始化与销毁
- java 配置
- JSR-250注解 PostConstruct构造函数执行后后 ,PreDestroy 销毁前
public class BeanWayService {
public void init(){
System.out.println("@Bean-init-method");
}
public BeanWayService() {
super();
System.out.println("初始化构造函数-BeanWayService");
}
public void destroy(){
System.out.println("@Bean-destory-method");
}
}
public class JSR250WayService {
@PostConstruct //1
public void init(){
System.out.println("jsr250-init-method");
}
public JSR250WayService() {
super();
System.out.println("初始化构造函数-JSR250WayService");
}
@PreDestroy //2
public void destroy(){
System.out.println("jsr250-destory-method");
}
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.prepost")
public class PrePostConfig {
@Bean(initMethod="init",destroyMethod="destroy") //1
BeanWayService beanWayService(){
return new BeanWayService();
}
@Bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
}
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(PrePostConfig.class);
BeanWayService beanWayService = context.getBean(BeanWayService.class);
JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
context.close();
}
}
profile
public class DemoBean {
private String content;
public DemoBean(String content) {
super();
this.content = content;
}
}
@Configuration
public class ProfileConfig {
@Bean
@Profile("dev") //1
public DemoBean devDemoBean() {
return new DemoBean("from development profile");
}
@Bean
@Profile("prod") //2
public DemoBean prodDemoBean() {
return new DemoBean("from production profile");
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod"); //1
context.register(ProfileConfig.class);//2
context.refresh(); //3
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
事件
一个bean处理完一个任务之后,另一个bean知道并处理
1,自定义事件 ApplicationEvent
public class DemoEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String msg;//get set
public DemoEvent(Object source,String msg) {
super(source);
this.msg = msg;
}
}
2,事件监听器 ApplicationListener
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMsg();
System.out.println("我(bean-demoListener)接受到了bean-demoPublisher发布的消息:"
+ msg);
}
}
3,事件发布类
@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String msg){
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
4,配置
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.event")
public class EventConfig {
}
5,运行
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
demoPublisher.publish("hello application event");
context.close();
}
第三章,spring高级话题,spring aware
让 Bean获得 Spring 容器的服务
@Service
public class AwareService implements BeanNameAware,ResourceLoaderAware{//1
private String beanName;
private ResourceLoader loader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {//2
this.loader = resourceLoader;
}//重写了资源加载器
@Override
public void setBeanName(String name) {//3
this.beanName = name;
}//重写了 setBeanName
public void outputResult(){
System.out.println("Bean的名称为:" + beanName);
Resource resource =
loader.getResource("classpath:test.txt");//com/wisely/highlight_spring4/ch3/aware/
try{
System.out.println("ResourceLoader加载的文件内容为: " + IOUtils.toString(resource.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
}
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.aware")
public class AwareConfig {
}
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();
}
}
多线程
@Service
public class AsyncTaskService {
@Async //1
public void executeAsyncTask(Integer i){
System.out.println("执行异步任务: "+i);
}
@Async
public void executeAsyncTaskPlus(Integer i){
System.out.println("执行异步任务+1: "+(i+1));
}
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskexecutor")
@EnableAsync //1
public class TaskExecutorConfig implements AsyncConfigurer{//2
@Override
public Executor getAsyncExecutor() {//2
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
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();
}
计划任务
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000) //1
public void reportCurrentTime() {
System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 28 11 ? * *" ) //2
public void fixTimeExecution(){
System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");
}
}
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")
@EnableScheduling //1
public class TaskSchedulerConfig {
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
}
}
条件注解
public class WindowsCondition implements Condition {
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
} //contains("Linux");
}
public interface ListService {
public String showListCmd();
}
public class WindowsListService implements ListService {
@Override
public String showListCmd() {
return "dir";
} // return "ls";
}
@Configuration
public class ConditionConifg {
@Bean
@Conditional(WindowsCondition.class) //1
public ListService windowsListService() {
return new WindowsListService();
}
@Bean
@Conditional(LinuxCondition.class) //2
public ListService linuxListService() {
return new LinuxListService();
}
}
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();
}
组合注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration //1
@ComponentScan //2
public @interface WiselyConfiguration {
String[] value() default {}; //3
}
//使用
@WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation")
public class DemoConfig {
}
@Service
public class DemoService {
public void outputResult(){
System.out.println("从组合注解配置照样获得的bean");
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(DemoConfig.class);
DemoService demoService = context.getBean(DemoService.class);
demoService.outputResult();
context.close();
}
测试
public class TestBean {
private String content;
public TestBean(String content) {
super();
this.content = content;
}
} //get set
@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");
}
}
@RunWith(SpringJUnit4ClassRunner.class) //1
@ContextConfiguration(classes = {TestConfig.class}) //2
@ActiveProfiles("prod") //3
public class DemoBeanIntegrationTests {
@Autowired //4
private TestBean testBean;
@Test //5
public void prodBeanShouldInject(){
String expected = "from production profile";
String actual = testBean.getContent();
Assert.assertEquals(expected, actual)
;
}
}