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.
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
Presentation from Dreamforce 2014 on using the Tooling API to create increased support for calling SOAP based web services using WSDLs to generate Apex.
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
Spring Certification Questions and Spring Free test are tests created to demonstrate all the functions of our mock exams. You will be able to access ten full questions and will have ten minutes of time for finishing the test.
There are several components you can interact with when you take our mock exams:
Take a look at the progress bar at the top; it will tell how you are progressing through the exam.
Read the question and select only the answers you think are correct by checking the corresponding check box.
Navigate the spring questions using the "Previous" and "Next" buttons.
Mark the spring questions you wish to review later. All the questions you have marked will be listed on the right in the section "marked questions". You will be able to jump directly to the question from this list.
If you want to take a look at the correct answers for a question, just click the "Solution" button. In the solution section you will be able to check your answers as well as find a full explanation of the question.
Keep an eye on the countdown. This will tell you how much time is remaining. When the countdown expires, the test will be automatically submitted.
Once the test is submitted, the "result" section will expand. Here, you will be able to review all the questions of the test. From here, you can also navigate directly to each question.
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
Presentation from Dreamforce 2014 on using the Tooling API to create increased support for calling SOAP based web services using WSDLs to generate Apex.
Introduction to JPA and Hibernate including examplesecosio GmbH
In this talk, held as part of the Web Engineering lecture series at Vienna University of Technology, we introduce the main concepts of Java Persistence API (JPA) and Hibernate.
The first part of the presentation introduces the main principles of JDBC and outlines the major drawbacks of JDBC-based implementations. We then further outline the fundamental principles behind the concept of object relation mapping (ORM) and finally introduce JPA and Hibernate.
The lecture is accompanied by practical examples, which are available on GitHub.
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
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.
This talk represents the combined experience from several web development teams who have been using Symfony2 since months already to create high profile production applications. The aim is to give the audience real world advice on how to best leverage Symfony2, the current rough spots and how to work around them. Aside from covering how to implement functionality in Symfony2, this talk will also cover topics such as how to best integrate 3rd party bundles and where to find them as well as how to deploy the code and integrate into the entire server setup.
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
A high-level description of mock testing techniques and their implementation for the Java programming language.
This presentation specifically focus on the JMockit and JMock frameworks.
Spring Framework Petclinic sample applicationAntoine Rey
Spring Petclinic is a sample application that has been designed to show how the Spring Framework can be used to build simple but powerful database-oriented applications.
The fork named Spring Framework Petclinic maintains a version both with a plain old Spring Framework configuration and a 3-layer architecture (i.e. presentation --> service --> repository).
Dependency injection is a powerful technique allowing different parts of a system to collaborate with each other. Injection is the passing of a dependency (such as a service or database connection) to an object that would use it. This way, the object need not change because the outside service changed. This often also allows the object to be more easily tested by injecting a mock or stub service as the dependency.
7.1 Identify which attribute scopes are thread-safe:
Local variables
Instance variables
Class variables
Request attributes
Session attributes
Context attributes
7.2 Identify correct statements about differences between the multithreaded and single-threaded servlet models.
7.3 Identify the interface used to declare that a servlet must use the single thread model.
This session will give attendees an overview of the new testing features in Spring 3.1 as well the new Spring MVC test support. Sam Brannen will demonstrate how to use the Spring TestContext Framework to write integration tests for Java-based Spring configuration using @Configuration classes. He'll then compare and contrast this approach with XML-based configuration and follow up with a discussion of the new testing support for bean definition profiles. Next, Rossen Stoyanchev will show attendees how testing server-side code with annotated controllers and client-side code with the RestTemplate just got a whole lot easier with the new Spring MVC test support. Come to this session to see these new Spring testing features in action and learn how you can get involved in the Spring MVC Test Support project.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
5. Annotation Config
Example
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://
www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/
beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/
spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/
context/spring-context-3.0.xsd">
<!--
Scans within the base package of the application for @Components to
configure as beans
-->
<context:component-scan base-package="com.tedpennings.bu.cs667" />
<mvc:annotation-driven />
</beans>
6. Annotation
Taxonomy
@Component and its specializations
@Service, @Repository
@Controller
@Configuration + @Bean
@Autowired
@Value
7. @Component
Example
@Component("rssView")
public class RomeRssView extends AbstractView {
@Override
protected void renderMergedOutputModel(Map model,
HttpServletRequest request, HttpServletResponse
response) throws Exception {
doStuff();
}
}
8. @Service Example
@Service
public class TwitterStatusProvider implements StatusProvider {
@Autowired
private CacheRepository cache;
@Override
public String getStatus(boolean skipCache) {
String status = cache.findString(CACHE_KEY);
if (skipCache || status == null) {
status = getStatusFromTwitter();
cache.cacheString(CACHE_KEY, status, DEFAULT_CACHE_EXPIRY);
}
return status;
}
}
9. @Configuration
Classes
Java classes that do the work of XML
Application Context files
Allow much more control over object creation
Instantiated before XML beans
@Configuration @Beans can be referenced by
XML beans/config
Can also reference XML beans
10. @Config Example
@Configuration
public class MongoConfiguration {
@Value("${db.host}")
private String dbHost;
@Value("${db.port}")
private int dbPort;
@Bean
@Lazy
public Mongo mongo() throws UnknownHostException {
return new Mongo(dbHost, dbPort);
}
}
11. MVC Changes
Controller interfaced dropped
@RequestMapping instead of XML config
@Controller instead of explicit XML config
Lots of return types possible
Simplicity
12. The Simplicity of
Controllers
@Controller makes a class a controller “bean”
Specialization of @Component
@RequestMapping defines the URL paths handled by a
class and/or method.
It is possible to nest paths, as in example on next slide.
Many different RequestMethods allowed in a @Controller
{} in @RM path define @PathVariable/@ReqParam
Value of Inheritance
Annotation caveat
13. @Controller Example
@Controller
@RequestMapping({ "/yacht", "/yachts", "/mah-boats" })
public class YachtController {
@Autowired
private YachtService service;
private static final String YACHT_PAGE_VIEW = "yachts/view";
@RequestMapping(value = "/{yachtKey}", method = GET)
public String displayYacht(@PathVariable(“yachtKey”) String yachtKey,
Model model) {
LOG.debug("Displaying Yacht " + yachtKey);
Yacht yacht = service.findYachtByKey(yachtKey);
model.addAttribute("yacht", yacht);
return YACHT_PAGE_VIEW;
}
}
14. MVC Annotations
@Controller – an MVC Controller
@RequestMapping
@ModelAttribute
@RequestParam and @PathVariable
@SessionAttributes
16. Controller Method
Return Types
@Controller methods can return many different types. Often:
Model
ModelAndView (use Model.setView(View) or
Model.setViewName(String))
Distinction between View and View Name
String for the view name to display
Can return void if you’ve drank plenty of convention over configuration
koolaid.
Dangerous if you refactor a lot (or the next person does).
Methods can also be annotated with @RequestBody
Used to return a value without going through MVC apparatus
Generally bad form, but good for testing or mock apps.
@ModelAttribute has the same two distinct meanings as @ModelAttribute
17. Bean Validation
(JSR-303)
Constraints are defined by @Entity
public class Yacht {
annotations on the actual data @Id
@GeneratedValue(strategy = GenerationType.AUTO)
entities private Long id;
Validation is executed @Size(min = 4, max = 35, message = "Key must be
between {min} and {max} characters long.")
automagically by framework @NotEmpty(message = "Key is required.")
@Pattern(regexp = "[A-Za-z0-9_-]*", message = "Only
letters, numbers, underscores and hyphens may be used.")
User-friendly errors appear private String key;
automagically on the view.
@Size(min = 4, max = 35, message = "Name must be
between {min} and {max} characters long.")
Object graphs can be traversed @NotEmpty(message = "Name is required.")
private String name;
and nested objects are validated
@ValidDate
(or not, if you wish). private Date acquisitionDate;
}
18. Setting Up And Using
Bean Validation
As simple as @Valid
Can be applied inside domain to validate child/2nd degree
objects
BindingResult for errors
MUST be argument after @Valid argument (quirk)
RuntimeException if not
toString() is your friend.
Validating a large object graph is risky.
Complicates future changes
On the other hand, very hard to merge BindingResults
19. Updated Controller
@Controller
public class YachtController {
@RequestMapping(method = POST)
public ModelAndView saveYacht(@Valid Yacht yacht, BindingResult
result, ModelAndView mv) {
LOG.debug("Attempting to save Yacht: " + yacht.getKey());
if (result.hasErrors()) {
LOG.debug("Submission has errors " + result);
mv.setViewName(MODIFY_YACHT_VIEW);
return mv;
}
service.store(yacht);
FlashMap.setSuccessMessage("Successfully saved Yacht");
return createRedirect(yacht);
}
}
20. Handling Validation
Errors
Ensure that you have a BindingResult.hasErrors() check in @Controller
When returning edit view, ensure all needed model attributes are present
This includes the object being validated if you construct a new Model/
MV
You may need a call to the root-level form:errors in order to capture object-
level errors (not field-level).
<form:errors path=“” />
Be sure you interrupt flow so you don’t persist invalid objects
VALIDATION ERRORS ARE NOT EXCEPTIONS
There is a Hibernate option to validate pre-persist, but this is nuanced
Legacy objects
May be incompatible with Spring-managed dependencies
21. Writing Your Own
Constraints
Constraints can be combined and composed
For example, @NotEmpty actually means @NotNull, @Size(min=1) &
@ReportAsSingleViolation
Write an annotation class
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented (or not)
@Constraint(validatedBy = YourCustomValidator.class)
Be sure to add a default message
These can be Java properties read from a file (Internationalization/i18n)
Write a validator
Implement ConstraintValidator<AnnotationType, TargetClass>
Return boolean for isValid(TargetClass object, …)
Statefulness (via initialize() method)
Dependency Injection, Constructors, and Hibernate ORM issue
22. Writing Unit Tests For Validation
Magic
A lot of JSR-303 is wizardry and magic beans.
Write unit tests so you ensure code execution is
predictable.
Easiest to write using Spring’s JUnit Test Runner
Point to an application context field that contains
<bean id="validator“
class="org.springframework.validation.beanvalidation.Loca
lValidatorFactoryBean" />
Ensure a JSR-303-compliant validator is on your test
classpath
Eg, Hibernate Validator
23. Example Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:your-persistence.xml",
"classpath:your-persistence-test.xml" })
public class YachtValidationTest {
@Autowired
private javax.validation.Validator validator;
private Yacht emptyYacht;
@Before
public void setUpEmptyYacht() {
emptyYacht = new Yacht();
}
@Test
public void theKeyFieldIsRequired() {
Set<ConstraintViolation<Yacht>> constraintViolations = validator
.validate(emptyYacht);
boolean containsYachtKeyViolation = false;
for (ConstraintViolation<Yacht> violation : constraintViolations) {
if ("key".equals(violation.getPropertyPath().toString())
&& violation.getMessageTemplate().contains("required")) {
containsYachtKeyViolation = true;
}
}
assertTrue(containsYachtKeyViolation);
}
}
24. Even More
Annotations
JSR 250 Resource Management
JSR 299/330 Bean Injection
JPA!
27. JPA Annotations
@PersistenceContext / @PersistenceUnit
@Entity
@Column, @Id, @Enumerated, @ManyToOne, etc
Mixes well with Spring-tx and @Transactional
28. Basic JPA Configuration
in Spring 3.0
PersistenceAnnotationBeanPostProcessor for
@PersistenceContext/Unit EntityManagers
LocalContainerEntityManagerFactoryBean to
bootstrap JPA and read persistence.xml
Still need to configure provider, eg, Hibernate
Need to provide data source, either as a
constructed bean or JNDI reference
\nThe createRedirect shown is a hack to avoid nasty exposed model attributes. Credit for this code goes to David Ehringer:\n\n private ModelAndView createRedirect(Yacht yacht) {\n String yachtKey = yacht.getKey();\n RedirectView redirect = new RedirectView("/yacht/" + yachtKey, true);\n // We are doing this rather than simply returning the String version of\n // the view (i.e. redirect:/groups/groupKey) because in the current\n // version of Spring all the model attributes get appended to the URL\n // which is nasty.\n redirect.setExposeModelAttributes(false);\n return new ModelAndView(redirect);\n }\n
\n
\n
Possibilities for ESAPI!\n
You can also use <mvc:annotation-driven />, but this often registers two conflicting instances of javax.validation.Validator, and causing an ambiguous bean reference exception on the @Autowired injection line in this example. It is easier to explicitly define an instance as above.\n