Spring Combat-fourth-4.4 declaring facets using XML and introducing new methods

Source: Internet
Author: User
Tags aop

When you cannot directly contact the source code, the same cannot add annotations to the source code, you can use XML to declare slices and introduce new methods

Compactdisc interface

 Package Main.java.soundsystem;  Public Interface Compactdisc {    void  play ();     void Playtrack (Integer tracknumber);}

BLANKDISC implementation

 PackageMain.java.soundsystem;Importjava.util.List; Public classBlankdiscImplementscompactdisc{PrivateString title; PrivateString artist; PrivateList<string>tracks;  PublicBlankdisc Settitle (String title) { This. title =title; return  This; }     PublicBlankdisc setartist (String artist) { This. Artist =artist; return  This; }     PublicString GetTitle () {returntitle; }     PublicString getartist () {returnartist; }     Public voidSettracks (list<string>tracks) {         This. Tracks =tracks; }     Public voidPlay () {System.out.println ("Playing" + title + "by" +artist); if(tracks!=NULL) {             for(String track:tracks) {System.out.println ("-track:" +Track ); } }} @Override Public voidPlaytrack (Integer tracknumber) {System.out.println ("Playing" +tracks.get (trackNumber-1)); }}

Trackcounter method (no annotations)

 PackageMain.java.soundsystem;ImportJava.util.HashMap;ImportJava.util.Map; Public classTrackcounter {PrivateMap<integer, integer> trackcounts =NewHashmap<integer, integer>();  Public voidTrackplayed (intTracknumber) {    }     Public voidCounttrack (intTracknumber) {        intCurrentcount =Getplaycount (Tracknumber); System.out.println ("Track:" +tracknumber); Trackcounts.put (Tracknumber, Currentcount+ 1); }     Public voidPrintmap () {Trackcounts.foreach (k, v)-System.out.println ("Key:" + K + ", Value:" +v)); }     Public intGetplaycount (intTracknumber) {        returnTrackcounts.containskey (tracknumber)? Trackcounts.get (Tracknumber): 0; }}

XML configuration File Declaration facets

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xsi:schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd            Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-co Ntext.xsd ">    <Context:component-scanBase-package= "Main.java.soundsystem"/>    <Aop:aspectj-autoproxy/>    <BeanID= "trackcounter|"class= "Main.java.soundsystem.TrackCounter"/>    <BeanID= "Blankdisc"class= "Main.java.soundsystem.BlankDisc">        < Propertyname= "title"value= "Sgt. Pepper ' s Lonely heart Club Band"/>        < Propertyname= "Artist"value= "The Beatles"/>        < Propertyname= "Tracks">            <List>                <value>Sgt Pepper ' s Lonely Hearts Club Band</value>                <value>With a Little help from My Friends</value>                <value>Lucy in the Sky with Diamonds</value>                <value>Getting Better</value>                <value>Fixing a Hole</value>            </List>        </ Property>    </Bean>    <Aop:config>        <Aop:aspectref= "trackcounter|">            <Aop:pointcutID= "Trackplayed"expression= "Execution (* Main.java.soundsystem.CompactDisc.playTrack (Integer)) and Arg S (tracknumber) " />            <Aop:beforePointcut-ref= "Trackplayed"Method= "Counttrack"/>        </Aop:aspect>        </Beans>

Test:

Package Main.java.soundsystem;import Org.springframework.beans.factory.annotation.autowired;import Static Org.junit.assert.*;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner, @RunWith (Springjunit4classrunner.class) @ Contextconfiguration (locations = "Classpath*:/trackcounterconfig.xml") public class Trackcountertest {@Autowired pri    Vate Compactdisc cd;    @Autowired Private Trackcounter counter;        @Test public void Testtrackcounter () {cd.playtrack (1);        Cd.playtrack (1);        Cd.playtrack (3);        Cd.playtrack (4);        Cd.playtrack (4);        Cd.playtrack (4);        Assertequals (2,counter.getplaycount (1));        Assertequals (1,counter.getplaycount (3)); Assertequals (3,counter.getplaycount (4));    }} 

Test output:

Track:1playing Sgt Pepper ' s Lonely Hearts club bandtrack:1playing Sgt Pepper ' s Lonely Hearts Club bandtrack:3playing Luc Y in the Sky with diamondstrack:4playing Getting bettertrack:4playing Getting bettertrack:4playing Getting betterprocess F Inished with exit code 0

Printer interface

 Package Main.java.soundsystem;  Public Interface Printer {    void  printcover ();}

Cdprinter class implements printer interface

 PackageMain.java.soundsystem; Public classCdprinterImplementsPrinter {@Override Public voidPrintcover () {System.out.println ("Print CD cover ..." +Time ); }     PublicString GetTime () {returnTime ; }     Publiccdprinter settime (String time) { time=Time ; return  This; }    PrivateString time;

Add a configuration to the XML configuration, introduce a new parent class for the Compactdisc interface class, and add a slice to the Aop:config configuration section

which

Types-matching: To add a new parent class to which interface,

Implement-interface: New Parent class

Default-impl: New default implementation of parent class

< Aop:aspect > < aop:declare-parents
  Types-matching= "Main.java.soundsystem.CompactDisc"
Implement-interface= "Main.java.soundsystem.Printer"
Default-impl= "Main.java.soundsystem.CDPrinter"/>
</aop:aspect>

Add test methods:

@Test      Public void Testprinter ()    {        new classpathxmlapplicationcontext ("Trackcounterconfig.xml");        Compactdisc cd= (compactdisc) context.getbean ("Blankdisc");        Cd.play ();        System.out.println ("\ncast to printer\n");        ((Printer) CD). Printcover ();    }

Output:

Playing Sgt Pepper's Lonely Heart Club Band by the Beatles-track:sgt Pepper ' s Lonely Hearts Club band-Track:with A Little help from My Friends-track:lucyin the Sky with Diamonds-track:getting Better-track: Fixing a holecast to Printerprint CD cover ... NULL  0

Spring Combat-fourth-4.4 declaring facets using XML and introducing new methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.