The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
This document provides an overview of Java EE technology, including:
- An introduction to Java programming language and its history.
- A description of core Java concepts like packages, inheritance, polymorphism.
- An explanation of Java EE platform and its main components like Servlets, JSF, EJBs.
- A discussion of how Java EE applications are packaged and deployed on an application server using modules.
- An overview of key Java EE concepts like containers, dependency injection and how they manage application components.
The goal is to give the reader a high-level understanding of the Java EE platform and technologies.
The document provides an introduction to Hibernate and demonstrates a basic "Hello World" example using Hibernate. It shows how to define a persistent class, save and retrieve data from the database using Hibernate, and configure Hibernate via properties files or XML. Key aspects of the Hibernate architecture like the SessionFactory, Session, and Transactions are also explained at a high level.
This document discusses new features and improvements in Spring 4. It covers Java 8 support including lambda expressions, date/time API updates, and optional types. It also summarizes core container improvements like meta annotations, generic qualifiers, and conditional bean configuration. General web improvements involving the @RestController annotation and Jackson serialization views are outlined. Testing improvements such as active profile resolution and the SocketUtils class are also mentioned.
Fifty Features of Java EE 7 in 50 Minutesglassfish
This document outlines 50 new features of Java EE 7 presented in 50 minutes. It begins with an overview listing the Java EE 7 specifications that have new features, such as JAX-RS 2.0, JSON-P 1.0, CDI 1.1, Bean Validation 1.1, Interceptors 1.2, Concurrency Utilities 1.0, JPA 2.1, JTA 1.2, and others. It then proceeds to briefly describe 16 new features across these specifications, including default CDI enabling, method validation in Bean Validation, interceptor bindings with priority in Interceptors, managed executors and scheduled executors in Concurrency Utilities, and schema generation and stored procedures in JPA.
This 50 minutes talk covers the novelties of Java EE 7 (easier to understand if you already know Java EE 6). It comes from the talk I gave with Arun Gupta at JavaOne 2013
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
While Java’s strict type system is a great help for avoiding programming errors, it also takes away some of the flexibility that developers appreciate when using dynamic languages. By using runtime code generation, it is possible to bring some of this flexibility back to the Java virtual machine. For this reason, runtime code generation is widely used by many state-of-the-art Java frameworks for implementing POJO-centric APIs but it also opens the door to assembling more modular applications. This presentation offers an introduction to the complex of runtime code generation and its use on the Java platform. Furthermore, it discusses the up- and downsides of several code generation libraries such as ASM, Javassist, cglib and Byte Buddy.
The document contains details of 9 practical assignments for an Advance Java course. Each practical assignment involves developing a Java program or application to demonstrate a concept. For example, Practical 01 involves creating a program to select stationary products and display prices; Practical 02 creates an editable employee table; Practical 03 uses a split pane to display planet images; and so on. The final practical involves developing a room reservation system using Enterprise Java Beans.
The document discusses improvements to caching in Spring 4.1, including support for JSR-107 annotations. Some key points:
- Spring now supports JCache (JSR-107) annotations like @CacheResult, which maps to Spring's @Cacheable.
- Examples show how to rewrite Spring caching code to use JSR-107 annotations, including customizing cache names and keys.
- Support for caching exceptions, cache resolvers, and default caching configurations are described.
- Enabling JSR-107 support requires adding the JCache API and spring-context-support dependencies.
Java 7 introduced several new features including underscore in numeric literals to improve readability (e.g. 1_000), binary literals prefixed with "0b", string switching to allow string comparisons, diamond operator <> in collections to simplify generic type instantiation, improved exception handling with multi-catch functionality, automatic resource management with try-with-resources, and new NIO 2.0 APIs including file change notifications. Other enhancements included fork/join framework for parallel programming, dynamic language support improvements, and Swing component decorator JLayer. The presentation proposed upgrading an existing Etrali project to Java 7 for benefits such as improved performance and reduced code size.
micro(-service) components. While this approach to building software - if done correctly - can improve a system's maintainability and scalability, distributed applications also introduce challanges for operations. Where monolithic applications typically offered direct access to extensive monitoring dashbords, such easy overview is no longer available when multitude services are loosly connected over a network. But how to keep track of a system of such dynamic state?
Distributed tracing is a method of connecting interaction of different services on a network. Collecting and processing such tracing information again allows for the observation of a distributed system in its entirety. This talk shares the presenter's insights gained by working on the JVM-support of distributed tracing for the APM tool Instana. Doing so, it introduces the landscape of distributed tracing on the JVM, discussing popular approaches such as Dapper, Zipkin or Brave/OpenTracing. In the process, it is discussed how byte code instrumentation can be used to capture systems without requiring a user to set up the software under observation. The presentation finishes with a discussion of typical problems of distributed tracing solutions and carefully examines the performance penalties APM tools entail.
Presented at BJUG, 6/12/2012 by Roger Brinkley
This talk is on 55 new features in Java 7 you (probably) didn't hear about in an ignite format of one per minute. No stopping, no going back....Questions, sure but only if time remains (otherwise save for later).
The document summarizes new features introduced in Java 5 and Java 6. Java 5 introduced generics, autoboxing/unboxing, enhanced for loops, and annotations. Java 6 added support for XML processing and web services using annotations, the Rhino JavaScript engine, improved GUI APIs, and Java DB for database connectivity.
The document provides an overview of new concepts and features in Java EE 6, including profiles like Web Profile 1.0 that define subsets of the platform, new specifications like Managed Beans 1.0 and Interceptors 1.1, and updates to existing specifications such as EJB 3.1, JPA 2.0, Servlet 3.0, and JSF 2.0. It discusses concepts like pruning of specifications, portable JNDI names, embeddable containers, and the move of Facelets as the preferred view definition language for JSF.
With its ninth version, the Java platform has shifted gear and introduced biyearly releases. This was followed by a license change where Oracle, the steward of Java, now publishes a commercial and a non-commercial release of the Java virtual machine while other vendors took more space to promote their alternative builds of the OpenJDK. And in another flood of news, the Java EE specification was terminated and resolved into the Jakarta EE namespace.
A lot has been happening in the traditionally conservative Java ecosystem, to say the least, and many users are wondering if they still can rely on the platform. This talk gives an overview of the Java ecosystem, summarizes the changes that have been, that to expect and why the evolution of the platform is good news to the community.
This document discusses Java bytecode manipulation techniques using unsafe, instrumentation, and Java agents. It covers areas where bytecode manipulation is commonly used like mocking, persistence, and security. It analyzes techniques for defining and transforming classes at runtime and discusses challenges like injecting state and working with modules. The document also proposes ideas to standardize testing support and provide a unified dynamic code generation concept in Java.
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
This document provides an overview of Java servlets, including:
- Servlets reside on the server-side and generate dynamic web pages. They handle HTTP requests and responses.
- Servlets have a lifecycle of initialization, processing requests, and destruction. The servlet receives a request from the web server, processes it, and returns a response which is sent back to the client.
- Servlets offer advantages over CGI like better performance through multithreading and portability through the Java programming language. Common servlet APIs and interfaces are described.
This session describes the overview on different types of spring containers. Here we can also find simple examples showing the demo to instantiate the containers.
The document discusses different approaches to separating layout from markup and behavior from markup in web development. It argues that using CSS for layout and JavaScript libraries like jQuery for behavior is better than older approaches that used HTML tables for layout or obtrusive JavaScript. Specifically, it shows how to open links in new windows by adding a "new_window" class rather than using JavaScript inline with the HTML or window.onload, which has disadvantages. The best solution presented is to use jQuery to bind a click handler to links with the "new_window" class.
The document discusses building mobile web applications. It covers topics like using valid HTML, CSS selectors in jQuery, hiding and showing elements, plugins, tips for mobile development. The presentation encourages using multiple platforms like websites, iPhone web apps, PhoneGap apps, Adobe AIR apps, and Opera widgets to build a complete mobile experience. It concludes by thanking the audience and providing contact details.
Gave a talk at StartCon about the future of Growth. I touch on viral marketing / referral marketing, fake news and social media, and marketplaces. Finally, the slides go through future technology platforms and how things might evolve there.
32 Ways a Digital Marketing Consultant Can Help Grow Your BusinessBarry Feldman
How can a digital marketing consultant help your business? In this resource we'll count the ways. 24 additional marketing resources are bundled for free.
Spring 3 emphasizes annotation configuration over XML. Key changes include support for JSR 250, 299/330, and 303 annotations as well as a simplified MVC framework with @Controller and @RequestMapping annotations. Validation is integrated using JSR 303 annotations and executed automatically by the framework. Configuration is also simplified through @Configuration classes and the @Bean annotation.
EJB 3.0 introduced major changes from previous EJB versions to address criticisms and simplify development. Key changes include support for POJO-based development with annotations, optional deployment descriptors, the removal of home interfaces, and a new entity persistence model based on Hibernate that allows for ORM-style development and querying. The presentation provides examples to illustrate how sessions, dependencies, interceptors, and entity relationships work in EJB 3.0 compared to previous versions.
The easy way to develop Java applications has always been the standard stack (Spring, JEE, SQL) that confirms the LAMP equivalent in Java-speak. This presentation compares this model with a real use case based on Guice, Jersey and AppEngine.
The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
Le temps est révolu où Java EE ne serait qu’à développer des applications de mise à jour de données, avec JSF / EJB / JPA. Aujourd’hui Java EE s’est assoupli et s’est ouvert sur le monde, avec CDI comme clé de voûte et a repoussé nos limites grâce à des capacités d’extension puissantes et faciles d’utilisation comme JCA.
Dans un premier temps, nous reviendrons rapidement sur la place de CDI dans JavaEE 7 et sur ses mécanismes d’extension. Dans un deuxième temps, nous verrons les techniques de connecteurs JCA et comment ils peuvent aussi constituer une possibilité d’ouverture simple à mettre en œuvre. JCA fournit des techniques pour gérer des connexions sortantes ou entrantes, sur des formats ou protocoles variés.
The world of open source libraries and tools is vast for Android developers. Writing apps using solely Android SDK is impractical. Libraries can help you in many ways. They can speed up your development, save you creating boilerplate code and dealing with platform fragmentation, simplify your code and make it more readable and maintainable. In the talk I’m showing how several truly useful libraries can help a developer.
Presented at MobCon Europe 2017.
This document provides an introduction to Spring Boot, including its objectives, key principles, and features. It discusses how Spring Boot enables building standalone, production-grade Spring applications with minimal configuration. It demonstrates creating a "Hello World" REST app with one Java class. It also covers auto-configuration, application configuration, testing, supported technologies, case studies, and other features like production readiness and remote shell access.
Slides accompanying a presentation on Dropwizard I gave at the DevIgnition conference ( www.devignition.com ) on April 29, 2016. The sample code is on GitHub at https://github.com/sleberknight/dropwizard-devignition-2016
Taming Core Data by Arek Holko, MacoscopeMacoscope
The document discusses best practices for working with Core Data in iOS applications. It covers 9 steps: 1) setting up Core Data, 2) accessing the managed object context, 3) creating NSManagedObject subclasses, 4) creating fetch requests, 5) integrating networking, 6) using NSFetchedResultsController, 7) protocolizing models, 8) using immutable models, and 9) modularizing the code. The overall message is that Core Data code should be organized cleanly using small, single-purpose classes and protocols to improve testability, separation of concerns, and code reuse.
Apache Wicket is constantly growing in popularity throughout all kinds of projects. However Wicket doesn't come out of the box with a built-in Java EE support. Integration to CDI is missing and the same is valid for Bean Validation support for example. This session demonstrates how you can user CDI, Conversations and Bean Validation together with Apache Wicket. The first part of the talk will consist of a small slide-driven theoretical part whereas the second part will consist of a coding session that demonstrates hands-on how to hook everything together.
Лаконічні та елегантні автоматизовані тести? Безболісний (майже) тестовий стек для UI веб-додатків? Більше часу, щоб випити кави/пограти у Cuphead/ подивитись у порожнечу?
Ми поговоримо про Lombok, Vavr, Owner, чому вам варто використовувати готові рішення та як зробити тести більш лаконічними та читабельними. Вам знадобиться Vaper та/або гіроборд.
You're on another typical JavaEE-based project, and you find yourself writing the same old infrastructure code. Are you wondering if there's a quicker way to incorporate the basics such as configuration, logging, and email into your application? If so, then this presentation is for you. By using a number of Apache utilities from
Commons, Logging, and other areas, you can learn how to stop re-inventing the wheel.
We'll start with a simple Struts 2 application and iteratively add the ability to:
• Use Commons Lang for String and Date utilities.
• Use Commons Property Configuration to setup and use application Properties.
• Use Commons Logging and Log4J to log messages.
• Generate Excel spreadsheets with POI.
• Use Velocity Templates and Commons Email to format and send email messages.
• Use HttpClient to invoke web apps with HTTP/S.
• Use Commons IOUtils to simplify accessing web content.
The document provides an introduction to JUnit testing in Java. It discusses how to set up a JUnit test with the AEM testing framework using the AemContextExtension. Key aspects covered include adding Sling models to the test context, loading mock JSON resources, and adapting requests to test Sling models. The anatomy of a JUnit test is explained with examples of setting up mocks, verifying expectations, and asserting results. Mocking and the Mockito framework are also introduced for simulating dependencies in tests.
The document discusses testing in Android applications. It recommends moving as much logic as possible to the Java Virtual Machine (JVM) to allow for easier unit testing. This includes business logic, models, and network code using Retrofit. It also suggests using Espresso for UI testing on Android and monkeyrunner for basic OS interaction testing. The document acknowledges testing on Android can be painful due to speed and fragmentation issues, and proposes compromises like helping quality assurance engineers with tools like the Bee library.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
The document discusses test integration and provides examples of how to use the jIntegrity library to simplify database integration testing. It shows how jIntegrity can load test data from XML files, execute SQL statements to insert, update, delete and clean data, and be configured through properties files. jIntegrity aims to provide flexibility, organization and reuse through its API and helper classes to help automate common database operations for integration testing.
The document provides an overview of the Android infrastructure and development environment. It discusses:
- The layers of an Android application including presentation, application logic, and domain layers.
- Key aspects of the Android runtime including the Dalvik VM, app lifecycle, resources and context handling.
- Libraries that help with common tasks like compatibility, fragments, networking and dependency injection including the Android Support Library, ActionBarSherlock, Retrofit, Dagger and RoboGuice.
- Alternatives for data storage like SQLite and ORM libraries like ORMLite and GreenDAO.
- Options for testing Android apps using the DVM, JVM, Robotium and Robolectric.
The document provides an overview of the Android infrastructure and key concepts:
(1) It describes the layers of an Android application including the presentation layer, application logic layer, and domain layer.
(2) It explains important Android concepts such as the Android runtime environment, Dalvik virtual machine, application lifecycle and activities, and use of contexts.
(3) It discusses alternatives for common tasks like dependency injection with RoboGuice and Dagger, handling resources and views with ButterKnife and AndroidAnnotations, and accessing data with SQLite and ORMLite.
(4) It also briefly covers testing approaches on the DVM and JVM using AndroidTestCase, Robotium, and Robolectric
Latest Tech Trends Series 2024 By EY IndiaEYIndia1
Stay ahead of the curve with our comprehensive Tech Trends Series! Explore the latest technology trends shaping the world today, from the 2024 Tech Trends report and top emerging technologies to their impact on business technology trends. This series delves into the most significant technological advancements, giving you insights into both established and emerging tech trends that will revolutionize various industries.
Challenges and Strategies of Digital Transformation.pptxwisdomfishlee
In an era where digital innovation is ubiquitous, executives from various corporations frequently seek insights into the tangible benefits that digital transformation can offer. This document outlines a comprehensive framework that elucidates the concept of digital transformation, highlighting its multifaceted dimensions and the pivotal roles it plays in enhancing business competitiveness.
Intel Unveils Core Ultra 200V Lunar chip .pdfTech Guru
Intel has made a significant breakthrough in the world of processors with the introduction of its Core Ultra 200V mobile processor series, codenamed Lunar Lake. This innovative processor marks a fundamental shift in the way Intel creates processors, with a high degree of aggregation, including memory-on-package (MoP). The Core Ultra 300 MX series is designed to power thin-and-light devices that are capable of handling the latest AI applications, including Microsoft's Copilot+ experiences.
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesSAI KAILASH R
Explore the advantages and disadvantages of blockchain technology in this comprehensive SlideShare presentation. Blockchain, the backbone of cryptocurrencies like Bitcoin, is revolutionizing various industries by offering enhanced security, transparency, and efficiency. However, it also comes with challenges such as scalability issues and energy consumption. This presentation provides an in-depth analysis of the key benefits and drawbacks of blockchain, helping you understand its potential impact on the future of technology and business.
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptxFwdays
I will share my personal experience of full-time development on wasm Blazor
What difficulties our team faced: life hacks with Blazor app routing, whether it is necessary to write JavaScript, which technology stack and architectural patterns we chose
What conclusions we made and what mistakes we committed
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdfSelfMade bd
Imagine being able to generate high-quality traffic and leads effortlessly. Sounds like a dream, right? Well, it’s not. It’s called LeadMagnet IQ, and it’s here to revolutionize your marketing efforts.
(Note: Download the paper about this software. After that, click on [Click for Instant Access] inside the paper, and it will take you to the sales page of the product.)
kk vathada _digital transformation frameworks_2024.pdfKIRAN KV
I'm excited to share my latest presentation on digital transformation frameworks from industry leaders like PwC, Cognizant, Gartner, McKinsey, Capgemini, MIT, and DXO. These frameworks are crucial for driving innovation and success in today's digital age. Whether you're a consultant, director, or head of digital transformation, these insights are tailored to help you lead your organization to new heights.
🔍 Featured Frameworks:
PwC's Framework: Grounded in Industry 4.0 with a focus on data and analytics, and digitizing product and service offerings.
Cognizant's Framework: Enhancing customer experience, incorporating new pricing models, and leveraging customer insights.
Gartner's Framework: Emphasizing shared understanding, leadership, and support teams for digital excellence.
McKinsey's 4D Framework: Discover, Design, Deliver, and De-risk to navigate digital change effectively.
Capgemini's Framework: Focus on customer experience, operational excellence, and business model innovation.
MIT’s Framework: Customer experience, operational processes, business models, digital capabilities, and leadership culture.
DXO's Framework: Business model innovation, digital customer experience, and digital organization & process transformation.
Top 12 AI Technology Trends For 2024.pdfMarrie Morris
Technology has become an irreplaceable component of our daily lives. The role of AI in technology revolutionizes our lives for the betterment of the future. In this article, we will learn about the top 12 AI technology trends for 2024.
COVID-19 and the Level of Cloud Computing Adoption: A Study of Sri Lankan Inf...AimanAthambawa1
The study’s main objective is to analyse the level of cloud computing adoption and usage during COVID-19 in Sri
Lanka, especially in Information Technology (IT) organisations. Using senior IT employees, this study investigates
what extent their organisation adopts with cloud computing, the level of cloud computing usage, current use of
cloud service model, usage of cloud deployment model, preferred cloud service providers and reasons for adopting
and not adopting cloud computing. The study also describes why cloud computing is a solution for new normal
situations and the cloud-enabled services used during and after the COVID-19 pandemic. The finding suggests
that 87.7% of the organisations currently use cloud-enabled services, whereas 12.3% do not and intend to adopt.
Considering the benefits, cloud computing is the solution post COVID-19 pandemic to run the business way
forward.
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
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 } }
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 = "catServlet", urlPatterns = "/cat", initParams = { @WebInitParam (name = "name", value = "bobo") })
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")).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 } }
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 … } }
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(); .. }