Spring学习随笔(2):Eclipse下Spring环境配置+入门项目

1 准备工作

(按需下载)

2 Spring IDE

help->Eclipse Marketplace->Find"Spring"->install

选择需要的项目安装,重启Eclipse.

安装完记得重启


3 导入所需的包

方法有多种,我贴下我的方法。

项目右键->build path->configure build path->Libraries->add Library->User Library->User Librarys

->New->输入Library name->add External JARs->选择需要的包

->在add Library处勾选刚才的Lib->finish->ok;

我这种办法好像比较麻烦.......

 

 

 

4 入门项目

完整目录

 

Performer.java

 1 package com.spring;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 
 6 public class Performer {
 7     private Instrument ins;
 8     public Performer(Instrument ins){
 9         this.ins=ins;            //与Violin紧密耦合
10     }
11     public void play(){
12         ins.play();
13     }
14 }
15 class Record{
16     private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
17     public void starttime(){
18         System.out.println(df.format(new Date()));
19     }
20     public void endtime(){
21         System.out.println(df.format(new Date()));
22     }
23 }
24 class Violin extends Instrument {
25 
26     public void play() {
27         System.out.println("Violin music!");
28     }
29 }
30 class Instrument {
31     void play(){};
32 }

PerformerMain.java

 

package com.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PerformerMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext apc = new ClassPathXmlApplicationContext("spring.xml");  
        Performer hello = (Performer) apc.getBean("performer");  
        hello.play();
    }

}

 

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="performer" class="com.spring.Performer">
        <constructor-arg ref="violin" />
    </bean>

    <bean id="violin" class="com.spring.Violin"></bean>
    <bean id="record" class="com.spring.Record"></bean>
    
    <aop:config>
        <aop:aspect ref="record">

            <aop:pointcut expression="execution(* com.spring.Performer.play(..))"  id="play"/>

            <aop:before method="starttime" pointcut-ref="play"/>
            <aop:after method="endtime" pointcut-ref="play"/>
        </aop:aspect>
    </aop:config>
</beans>   

运行结果:


 

 

注意事项:

 xml文件中使用aop标签引入头文件配置

报错:

需要AspectJ的三个包,已在开头给出。


 

posted @ 2017-12-01 20:30  郑某某i  阅读(506)  评论(0编辑  收藏  举报