(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
JavaTWO  專業技術大會 Java Annotation 李日貴 (jini)
About Me jini@JWorld.TW ( jakarta99 ) SoftLeader Tech. Corp. President since 2002 Focus on dev in Java enterprise applications for Insurances, Banking and Betting. Researching and Sharing Java Opensources My Google+ ( http://gplus.to/jakarta99 ) Single now
Agenda Introduction Servlet 3.0 EJB 3.1 WebServices CDI Opensources Javassist / ASM
@Annotation Course1 Introduction
What’s annotation Begin with “@”  An Interface Set Values @Annotation @Annotation(“someValue”) @Annotation(var1=“someA”,var2=“someB”) @Annotation(value={“Apple”, “Banana”, “Cherry”})
RetentionPolicy
@Annotation Runtime Default value Stereotype Find the classes contain @Annotation Initialize them as what you want To generate the codes or xml and etc..
 
@Target(ElementType) @AnnoTarget( TYPE ) public class TheTarget { @AnnoTarget( FIELD ) private String globalMsg; @AnnoTarget( CONSTRUCTOR ) public TheTarget() { // This is a constructor } @AnnoTarget( METHOD ) public void someMethod ( @AnnoTarget ( PARAMETER )   String myParam) { // This is a method } }
@Annotation Course 2  Servlet 3.0
Servlet 2.5 package  javatwo.annotation ; public class  CatServlet  extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException  { // do something } } web.xml <web-app> <servlet> <servlet-name> CatServlet </servlet-name> <servlet-class> javatwo.annotation.CatServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> CatServlet </servlet-name> < url-pattern >/cat</ url-pattern > </servlet-mapping> </web-app>
Servlet 3.0 package  javatwo.annotation ; @WebServlet(“/cat”) public class  CatServlet  extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // do something } } @WebServlet (name = &quot;catServlet&quot;, urlPatterns = &quot;/cat&quot;,   initParams = {  @WebInitParam (name = &quot;name&quot;, value = &quot;bobo&quot;) })
Servlet 3.0 No web.xml needed @WebServlet - Define a Servlet @WebFilter - Define a Filter @WebListener   - Define a Listener @WebInitParam - Define init parameter @MultipartConfig -  Define upload properties Can use web.xml to override values that specified by the Annotations.
FileUpload in Servlet 3.0 @WebServlet(“/upload”) @MultipartConfig(location=“c:tmp”) public class FileUploadServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection< Part > parts =  request.getParts(); for( Part part:parts) { part.write(“upload.txt”);  // save to c:mppload.txt } }
set Async in Servlet 3.0 @WebServlet(name=“AsyncServlet”, urlPatterns=“/async”,  asyncSupported=“true”) public class AsyncServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { AsyncContext aCtx = request.startAsync(request, response);  ServletContext sc = request.getServletContext(); ((Queue<AsyncContext>)sc.getAttribute(“slowQueue&quot;)).add(aCtx); } } @WebListener public class SlowQueueListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { … } }
@Annotation Course 3  EJB 3.1
EJB 2.x public interface CalculatorLocal extends EJBLocalObject {..} public interface CalculatorLocalHome extends EJBLocalHome {..} public class CalculatorBean implements SessionBean { .. } ejb-jar.xml <ejb-jar> <enterprise-beans> <session> <ejb-name>calculator</ejb-name> <local-home>CalculatorLocalHome</local-home> <local>CalculatorLocal</local> <ejb-class>CalculatorBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar>
EJB 3.0 @Local  public interface CalculatorLocal  extends EJBLocalObject  {..} public interface CalculatorHome extends EJBHome {..} @Stateless  public class CalculatorBean implements CalculatorLocal{ .. } ejb-jar.xml
EJB 3.1 (LocalBean) @Local  public interface CalculatorLocal extends EJBLocalObject {..} public interface CalculatorHome extends EJBHome {..} @Stateless  public class CalculatorBean  implements CalculatorLocal { .. } ejb-jar.xml
Singleton SessionBean @Singleton @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) public class SingletonBean { private int clickCount = 0; @Lock(LockType.WRITE) public int getClickCount() { return clickCount++; } } //Thread-Safe, Transactional
Schedule Timer @Singleton public class TransFileBean { @Schedule(minute=“0”,hour=“4”,dayOfMonth=“Last”) public void trans() { // do transfer } }
@Annotation Course 4  WebServices
WebServices “ Big” WebServices SOAP JAX-WS javax.jws.* RESTful WebServices REST JAX-RS javax.ws.rs.*
SOAP WebService import  javax.jws. WebMethod; import  javax.jws. WebService; @WebService(serviceName=“helloService”) public class Hello { @WebMethod public String sayHello(String name) { return “Hello “+name; } }
 
RESTful WebService import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path(&quot;/helloREST/{ name }&quot;) public class HelloREST { @GET @Produces(MediaType.TEXT_PLAIN) public String getHello (@PathParam(&quot; name &quot;)  String name) { return &quot;Hello *&quot;+name+&quot;* from JAX-RS&quot;; } }
 
@Annotation Course 5  CDI
Resource Injection JEE5 @WebServlet(“/product”) public ProductServlet extends HttpServlet { @Inject private ProductBean productBean; .. } @Stateless public class ProductBean { .. }
Ambiguous Inject @Qualifier public @interface CarPolicyNo { } @Qualifier public @interface FirePolicyNo { } @CarPolicyNoGenerator public class CarPolicyNoGenerator implements PolicyNoGenerator {.. } @FirePolicyNoGenerator public class FirePolicyNoGenerator implements PolicyNoGenerator{ .. } public class FireService { @Inject @FirePolicyNoGenerator private PolicyNoGenerator policyNoGenerator; }
@Produces public class DatabaseProducer { @Produces  @PersistenceContext(unitName=“ds1”) @FireDatabase private EntityManager em; } public class FireService { @Inject   @FireDatabase private EntityManager em; }
@Annotation Course 6  Opensources
jUnit 3.x import junit.framework.Assert; import junit.framework.TestCase; public class CalculateServiceTest3  extends TestCase  { public void  setUp () throws Exception { } public void  test Sum() { int actual = new CalculateService().sum(3,5); Assert.assertEquals( 8 , actual ); } public void  tearDown () throws Exception { } }
jUnit 4.x public class CalculateServiceTest4  extends TestCase  { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void beforeTest() throws Exception {  } @Test public void theSum() { Assert.assertEquals(8, new CalculateService().sum(3, 5)) ;   }  @After public void afterTest() throws Exception {  } @AfterClass public static void tearDownAfterClass() throws Exception {  } }
 
Spring 2.5 <beans> <bean id=“newsDao” class=“javatwo.annotation.spring.NewsDao”/> <bean id=“newsService” class=“javatwo.annotation.spring.NewsService”> <property name=“newsDao”> <ref bean=“newsDao”/> </property> </bean> </beans> @Service public class NewsService { @Autowired private NewsDao newsDao; }
Spring 3.0 @Named public class NewsService { @Inject private NewsDao newsDao; }
Spring 3.0 @Configuration public class AppConfig { private  @Value(“#{sysprop.dbURL}”)  String dbURL; private  @Value(“#{sysprop.username}”)  String username; private  @Value(“#{sysprop.password}”)  String password; @Bean public DataSource dataSource() { return new DriverManagerDataSource(dbURL, username, password ); } }
MVC in Spring3.0 @Controller @RequestMapping(“/news”) public class NewsController { @RequestMaaping(value=“{id}”,  method=RequestMethod.GET)   public ModelAndView getById( @PathVariable(“id”)  Long id) { return … } }
@Annotation Course 7  Javassist / ASM
Reflection Class myClass = MyClass.class; Method[] myMethods = myClass. getMethods() ; for(Method myMethod:myMethods) { Annotation[]  annotations = myMethod. getAnnotations (); for(  Annotation  annotation:annotations) { if( annotation  instanceof   MyAnno  ) { MyAnno  myAnno = ( MyAnno ) annotation; // do something } } }
Scan in ClassLoader scannotation.sf.net project ( based on javassist ) URL[] urls = ClasspathUrlFinder.findClassPaths(); AnnotationDB db = new AnnotationDB(); db. scanArchives (urls); Map<String, Set<String>> annoIndex = db.getAnnotationIndex(); Set<String> aClassNames = annoIndex.get( “javatwo.annotation.MyAnno” ); for( String aClassName:aClassNames ) { .. } // in Web, WarUrlFinder. findWebInfClassesPath ( this .getServletContext());
Get the Annotation values ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(this.getClass)); CtClass  cc = pool.get(aClassName); Object[] annos = cc.getAnnotations(); for( Object anno : annos ) { if( anno instanceof MyAnno ) { MyAnno myAnno = (MyAnno) anno; // do myAnno.var1(), myAnno.var2() } }
Class R/W in ASM public class  ScanMyDocVisitor   implements   ClassVisitor  { public  AnnotationVisistor  visitAnnotation(String desc, boolean visible) { } } // in Controller for(String className: classNames){ ScanMyDocVisitor  sv = new  ScanMyDocVisitor (); ClassReader  cr = new ClassReader(Thread.currentThread().getContextClassLoader().getResouceAsStream(className)); cr.accept(sv, 0); List<AnnotationNode> annotationList  = sv.getVisibleAnnotations(); .. }
 

More Related Content

What's hot

Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
Francesco Nolano
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
sourabh aggarwal
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
glassfish
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
Antonio Goncalves
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Java7
Java7Java7
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5
IndicThreads
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
Rafael Winterhalter
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
Boulder Java User's Group
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
Jussi Pohjolainen
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
Antonio Goncalves
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
Rafael Winterhalter
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
Rafael Winterhalter
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
IndicThreads
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
Sunil kumar Mohanty
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
Sunil kumar Mohanty
 

What's hot (20)

Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
Java7
Java7Java7
Java7
 
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
 
Java servlets
Java servletsJava servlets
Java servlets
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 

Viewers also liked

jQuery SUG Group Introduction
jQuery SUG Group IntroductionjQuery SUG Group Introduction
jQuery SUG Group Introduction
Andrew Chalkley
 
千呼萬喚始出來的Java SE 7
千呼萬喚始出來的Java SE 7千呼萬喚始出來的Java SE 7
千呼萬喚始出來的Java SE 7
javatwo2011
 
Pimp your site with jQuery!
Pimp your site with jQuery!Pimp your site with jQuery!
Pimp your site with jQuery!
Elliott Kember
 
使用Hudson打造屬於你自己的軟體建構機器人
使用Hudson打造屬於你自己的軟體建構機器人使用Hudson打造屬於你自己的軟體建構機器人
使用Hudson打造屬於你自己的軟體建構機器人
javatwo2011
 
Twiggy - let's get our widget on!
Twiggy - let's get our widget on!Twiggy - let's get our widget on!
Twiggy - let's get our widget on!
Elliott Kember
 
用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services
javatwo2011
 
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
MIS2000 Lab.
 
What's Next in Growth? 2016
What's Next in Growth? 2016What's Next in Growth? 2016
What's Next in Growth? 2016
Andrew Chen
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
Barry Feldman
 

Viewers also liked (9)

jQuery SUG Group Introduction
jQuery SUG Group IntroductionjQuery SUG Group Introduction
jQuery SUG Group Introduction
 
千呼萬喚始出來的Java SE 7
千呼萬喚始出來的Java SE 7千呼萬喚始出來的Java SE 7
千呼萬喚始出來的Java SE 7
 
Pimp your site with jQuery!
Pimp your site with jQuery!Pimp your site with jQuery!
Pimp your site with jQuery!
 
使用Hudson打造屬於你自己的軟體建構機器人
使用Hudson打造屬於你自己的軟體建構機器人使用Hudson打造屬於你自己的軟體建構機器人
使用Hudson打造屬於你自己的軟體建構機器人
 
Twiggy - let's get our widget on!
Twiggy - let's get our widget on!Twiggy - let's get our widget on!
Twiggy - let's get our widget on!
 
用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services
 
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境從SOA到REST -- Web Service、WCF、WebAPI的應用情境
從SOA到REST -- Web Service、WCF、WebAPI的應用情境
 
What's Next in Growth? 2016
What's Next in Growth? 2016What's Next in Growth? 2016
What's Next in Growth? 2016
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Similar to 比XML更好用的Java Annotation

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
Dan Hinojosa
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
JUnit 5
JUnit 5JUnit 5
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
Alexis Hassler
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
Macoscope
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
Michael Plöd
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
Tom Marrs
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Daniel Bryant
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
Domenico Briganti
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 

Similar to 比XML更好用的Java Annotation (20)

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 

Recently uploaded

Perth MuleSoft Meetup July 2024
Perth MuleSoft Meetup July 2024Perth MuleSoft Meetup July 2024
Perth MuleSoft Meetup July 2024
Michael Price
 
Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17
Bhajan Mehta
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
FIDO Alliance
 
Latest Tech Trends Series 2024 By EY India
Latest Tech Trends Series 2024 By EY IndiaLatest Tech Trends Series 2024 By EY India
Latest Tech Trends Series 2024 By EY India
EYIndia1
 
Challenges and Strategies of Digital Transformation.pptx
Challenges and Strategies of Digital Transformation.pptxChallenges and Strategies of Digital Transformation.pptx
Challenges and Strategies of Digital Transformation.pptx
wisdomfishlee
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
FIDO Alliance
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
Tech Guru
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
Fwdays
 
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partesExchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
jorgelebrato
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
SelfMade bd
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
KIRAN KV
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
ZachWylie3
 
Top 12 AI Technology Trends For 2024.pdf
Top 12 AI Technology Trends For 2024.pdfTop 12 AI Technology Trends For 2024.pdf
Top 12 AI Technology Trends For 2024.pdf
Marrie Morris
 
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
OnBoard
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
CheckPoint Firewall Presentation CCSA.pdf
CheckPoint Firewall Presentation CCSA.pdfCheckPoint Firewall Presentation CCSA.pdf
CheckPoint Firewall Presentation CCSA.pdf
ssuser137992
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
isBullShit
 
History and Introduction for Generative AI ( GenAI )
History and Introduction for Generative AI ( GenAI )History and Introduction for Generative AI ( GenAI )
History and Introduction for Generative AI ( GenAI )
Badri_Bady
 
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
AimanAthambawa1
 

Recently uploaded (20)

Perth MuleSoft Meetup July 2024
Perth MuleSoft Meetup July 2024Perth MuleSoft Meetup July 2024
Perth MuleSoft Meetup July 2024
 
Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
 
Latest Tech Trends Series 2024 By EY India
Latest Tech Trends Series 2024 By EY IndiaLatest Tech Trends Series 2024 By EY India
Latest Tech Trends Series 2024 By EY India
 
Challenges and Strategies of Digital Transformation.pptx
Challenges and Strategies of Digital Transformation.pptxChallenges and Strategies of Digital Transformation.pptx
Challenges and Strategies of Digital Transformation.pptx
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptx
 
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partesExchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
Exchange, Entra ID, Conectores, RAML: Todo, a la vez, en todas partes
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
 
Top 12 AI Technology Trends For 2024.pdf
Top 12 AI Technology Trends For 2024.pdfTop 12 AI Technology Trends For 2024.pdf
Top 12 AI Technology Trends For 2024.pdf
 
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
Mastering Board Best Practices: Essential Skills for Effective Non-profit Lea...
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
CheckPoint Firewall Presentation CCSA.pdf
CheckPoint Firewall Presentation CCSA.pdfCheckPoint Firewall Presentation CCSA.pdf
CheckPoint Firewall Presentation CCSA.pdf
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
 
History and Introduction for Generative AI ( GenAI )
History and Introduction for Generative AI ( GenAI )History and Introduction for Generative AI ( GenAI )
History and Introduction for Generative AI ( GenAI )
 
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...
 

比XML更好用的Java Annotation

  • 1. JavaTWO 專業技術大會 Java Annotation 李日貴 (jini)
  • 2. About Me jini@JWorld.TW ( jakarta99 ) SoftLeader Tech. Corp. President since 2002 Focus on dev in Java enterprise applications for Insurances, Banking and Betting. Researching and Sharing Java Opensources My Google+ ( http://gplus.to/jakarta99 ) Single now
  • 3. Agenda Introduction Servlet 3.0 EJB 3.1 WebServices CDI Opensources Javassist / ASM
  • 5. What’s annotation Begin with “@” An Interface Set Values @Annotation @Annotation(“someValue”) @Annotation(var1=“someA”,var2=“someB”) @Annotation(value={“Apple”, “Banana”, “Cherry”})
  • 7. @Annotation Runtime Default value Stereotype Find the classes contain @Annotation Initialize them as what you want To generate the codes or xml and etc..
  • 8.  
  • 9. @Target(ElementType) @AnnoTarget( TYPE ) public class TheTarget { @AnnoTarget( FIELD ) private String globalMsg; @AnnoTarget( CONSTRUCTOR ) public TheTarget() { // This is a constructor } @AnnoTarget( METHOD ) public void someMethod ( @AnnoTarget ( PARAMETER ) String myParam) { // This is a method } }
  • 10. @Annotation Course 2 Servlet 3.0
  • 11. Servlet 2.5 package javatwo.annotation ; public class CatServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // do something } } web.xml <web-app> <servlet> <servlet-name> CatServlet </servlet-name> <servlet-class> javatwo.annotation.CatServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> CatServlet </servlet-name> < url-pattern >/cat</ url-pattern > </servlet-mapping> </web-app>
  • 12. Servlet 3.0 package javatwo.annotation ; @WebServlet(“/cat”) public class CatServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // do something } } @WebServlet (name = &quot;catServlet&quot;, urlPatterns = &quot;/cat&quot;, initParams = { @WebInitParam (name = &quot;name&quot;, value = &quot;bobo&quot;) })
  • 13. Servlet 3.0 No web.xml needed @WebServlet - Define a Servlet @WebFilter - Define a Filter @WebListener - Define a Listener @WebInitParam - Define init parameter @MultipartConfig - Define upload properties Can use web.xml to override values that specified by the Annotations.
  • 14. FileUpload in Servlet 3.0 @WebServlet(“/upload”) @MultipartConfig(location=“c:tmp”) public class FileUploadServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection< Part > parts = request.getParts(); for( Part part:parts) { part.write(“upload.txt”); // save to c:mppload.txt } }
  • 15. set Async in Servlet 3.0 @WebServlet(name=“AsyncServlet”, urlPatterns=“/async”, asyncSupported=“true”) public class AsyncServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { AsyncContext aCtx = request.startAsync(request, response); ServletContext sc = request.getServletContext(); ((Queue<AsyncContext>)sc.getAttribute(“slowQueue&quot;)).add(aCtx); } } @WebListener public class SlowQueueListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { … } }
  • 17. EJB 2.x public interface CalculatorLocal extends EJBLocalObject {..} public interface CalculatorLocalHome extends EJBLocalHome {..} public class CalculatorBean implements SessionBean { .. } ejb-jar.xml <ejb-jar> <enterprise-beans> <session> <ejb-name>calculator</ejb-name> <local-home>CalculatorLocalHome</local-home> <local>CalculatorLocal</local> <ejb-class>CalculatorBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar>
  • 18. EJB 3.0 @Local public interface CalculatorLocal extends EJBLocalObject {..} public interface CalculatorHome extends EJBHome {..} @Stateless public class CalculatorBean implements CalculatorLocal{ .. } ejb-jar.xml
  • 19. EJB 3.1 (LocalBean) @Local public interface CalculatorLocal extends EJBLocalObject {..} public interface CalculatorHome extends EJBHome {..} @Stateless public class CalculatorBean implements CalculatorLocal { .. } ejb-jar.xml
  • 20. Singleton SessionBean @Singleton @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) public class SingletonBean { private int clickCount = 0; @Lock(LockType.WRITE) public int getClickCount() { return clickCount++; } } //Thread-Safe, Transactional
  • 21. Schedule Timer @Singleton public class TransFileBean { @Schedule(minute=“0”,hour=“4”,dayOfMonth=“Last”) public void trans() { // do transfer } }
  • 22. @Annotation Course 4 WebServices
  • 23. WebServices “ Big” WebServices SOAP JAX-WS javax.jws.* RESTful WebServices REST JAX-RS javax.ws.rs.*
  • 24. SOAP WebService import javax.jws. WebMethod; import javax.jws. WebService; @WebService(serviceName=“helloService”) public class Hello { @WebMethod public String sayHello(String name) { return “Hello “+name; } }
  • 25.  
  • 26. RESTful WebService import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path(&quot;/helloREST/{ name }&quot;) public class HelloREST { @GET @Produces(MediaType.TEXT_PLAIN) public String getHello (@PathParam(&quot; name &quot;) String name) { return &quot;Hello *&quot;+name+&quot;* from JAX-RS&quot;; } }
  • 27.  
  • 29. Resource Injection JEE5 @WebServlet(“/product”) public ProductServlet extends HttpServlet { @Inject private ProductBean productBean; .. } @Stateless public class ProductBean { .. }
  • 30. Ambiguous Inject @Qualifier public @interface CarPolicyNo { } @Qualifier public @interface FirePolicyNo { } @CarPolicyNoGenerator public class CarPolicyNoGenerator implements PolicyNoGenerator {.. } @FirePolicyNoGenerator public class FirePolicyNoGenerator implements PolicyNoGenerator{ .. } public class FireService { @Inject @FirePolicyNoGenerator private PolicyNoGenerator policyNoGenerator; }
  • 31. @Produces public class DatabaseProducer { @Produces @PersistenceContext(unitName=“ds1”) @FireDatabase private EntityManager em; } public class FireService { @Inject @FireDatabase private EntityManager em; }
  • 32. @Annotation Course 6 Opensources
  • 33. jUnit 3.x import junit.framework.Assert; import junit.framework.TestCase; public class CalculateServiceTest3 extends TestCase { public void setUp () throws Exception { } public void test Sum() { int actual = new CalculateService().sum(3,5); Assert.assertEquals( 8 , actual ); } public void tearDown () throws Exception { } }
  • 34. jUnit 4.x public class CalculateServiceTest4 extends TestCase { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void beforeTest() throws Exception { } @Test public void theSum() { Assert.assertEquals(8, new CalculateService().sum(3, 5)) ; } @After public void afterTest() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } }
  • 35.  
  • 36. Spring 2.5 <beans> <bean id=“newsDao” class=“javatwo.annotation.spring.NewsDao”/> <bean id=“newsService” class=“javatwo.annotation.spring.NewsService”> <property name=“newsDao”> <ref bean=“newsDao”/> </property> </bean> </beans> @Service public class NewsService { @Autowired private NewsDao newsDao; }
  • 37. Spring 3.0 @Named public class NewsService { @Inject private NewsDao newsDao; }
  • 38. Spring 3.0 @Configuration public class AppConfig { private @Value(“#{sysprop.dbURL}”) String dbURL; private @Value(“#{sysprop.username}”) String username; private @Value(“#{sysprop.password}”) String password; @Bean public DataSource dataSource() { return new DriverManagerDataSource(dbURL, username, password ); } }
  • 39. MVC in Spring3.0 @Controller @RequestMapping(“/news”) public class NewsController { @RequestMaaping(value=“{id}”, method=RequestMethod.GET) public ModelAndView getById( @PathVariable(“id”) Long id) { return … } }
  • 40. @Annotation Course 7 Javassist / ASM
  • 41. Reflection Class myClass = MyClass.class; Method[] myMethods = myClass. getMethods() ; for(Method myMethod:myMethods) { Annotation[] annotations = myMethod. getAnnotations (); for( Annotation annotation:annotations) { if( annotation instanceof MyAnno ) { MyAnno myAnno = ( MyAnno ) annotation; // do something } } }
  • 42. Scan in ClassLoader scannotation.sf.net project ( based on javassist ) URL[] urls = ClasspathUrlFinder.findClassPaths(); AnnotationDB db = new AnnotationDB(); db. scanArchives (urls); Map<String, Set<String>> annoIndex = db.getAnnotationIndex(); Set<String> aClassNames = annoIndex.get( “javatwo.annotation.MyAnno” ); for( String aClassName:aClassNames ) { .. } // in Web, WarUrlFinder. findWebInfClassesPath ( this .getServletContext());
  • 43. Get the Annotation values ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(this.getClass)); CtClass cc = pool.get(aClassName); Object[] annos = cc.getAnnotations(); for( Object anno : annos ) { if( anno instanceof MyAnno ) { MyAnno myAnno = (MyAnno) anno; // do myAnno.var1(), myAnno.var2() } }
  • 44. Class R/W in ASM public class ScanMyDocVisitor implements ClassVisitor { public AnnotationVisistor visitAnnotation(String desc, boolean visible) { } } // in Controller for(String className: classNames){ ScanMyDocVisitor sv = new ScanMyDocVisitor (); ClassReader cr = new ClassReader(Thread.currentThread().getContextClassLoader().getResouceAsStream(className)); cr.accept(sv, 0); List<AnnotationNode> annotationList = sv.getVisibleAnnotations(); .. }
  • 45.