#spring runtime dependency injection
Explore tagged Tumblr posts
Text
Must-Know Core Java Concepts for Every Programmer
(A Guide for Full Stack Software Testing Enthusiasts in KPHB)
Java remains the backbone of enterprise applications, and a strong grasp of its core concepts is essential for every programmer. Whether you are an aspiring software tester, a backend developer, or a full-stack engineer, understanding Java fundamentals is non-negotiable. Let’s break down the most crucial Java concepts that you must master.

1. Object-Oriented Programming (OOP)
Java is inherently object-oriented, which means everything revolves around objects and classes. The four key pillars of OOP in Java are:
✔ Encapsulation – Bundling data and methods together to protect data integrity. ✔ Abstraction – Hiding implementation details and exposing only what’s necessary. ✔ Inheritance – Allowing one class to derive properties from another. ✔ Polymorphism – Enabling multiple implementations of a method.
Why It Matters?
For software testers, understanding OOP principles helps in creating reusable and scalable test automation frameworks.
2. Java Memory Management
Memory management is a crucial aspect that determines the performance of Java applications. It consists of:
✔ Heap & Stack Memory – Heap stores objects, while Stack holds method calls and local variables. ✔ Garbage Collection (GC) – Java has an automatic garbage collector that frees up memory by removing unused objects.
Why It Matters?
Full Stack Testers must understand memory leaks and performance bottlenecks in Java-based applications.
3. Exception Handling
Exception handling ensures that runtime errors don’t crash the application. Java provides:
✔ try-catch-finally – Handles exceptions and ensures resource cleanup. ✔ throws & throw – Used for explicitly handling custom exceptions. ✔ Checked vs. Unchecked Exceptions – Checked exceptions (like IOException) must be handled, while unchecked exceptions (like NullPointerException) occur at runtime.
Why It Matters?
Testers need to handle exceptions effectively in automation scripts to avoid script failures.
4. Multithreading & Concurrency
Multithreading allows multiple parts of a program to run simultaneously. Important concepts include:
✔ Thread Lifecycle – From creation to termination. ✔ Runnable & Callable Interfaces – Implementing threads in Java. ✔ Synchronization & Locks – Avoiding race conditions and ensuring thread safety.
Why It Matters?
In performance testing, understanding multithreading helps simulate real-world user load.
5. Collections Framework
Java provides a robust Collections Framework for handling groups of objects efficiently. The key interfaces are:
✔ List (ArrayList, LinkedList) – Ordered and allows duplicates. ✔ Set (HashSet, TreeSet) – Unordered and doesn’t allow duplicates. ✔ Map (HashMap, TreeMap) – Stores key-value pairs.
Why It Matters?
Test automation frameworks use collections extensively for data handling and assertions.
6. File Handling & I/O Operations
File handling is critical for reading, writing, and manipulating files in Java.
✔ BufferedReader & BufferedWriter – Efficient file reading and writing. ✔ FileInputStream & FileOutputStream – Handling binary data. ✔ Serialization – Converting objects into byte streams.
Why It Matters?
For automation testers, handling logs, reports, and configuration files is a routine task.
7. JDBC & Database Connectivity
Java Database Connectivity (JDBC) allows applications to interact with databases.
✔ DriverManager – Manages database connections. ✔ PreparedStatement – Prevents SQL injection. ✔ ResultSet – Retrieves query results.
Why It Matters?
Full Stack Testers should understand JDBC for validating database operations in automation scripts.
8. Java Frameworks
Mastering Java alone isn’t enough; knowing key frameworks is essential.
✔ Spring Boot – Microservices and dependency injection. ✔ Selenium with Java – Web automation testing. ✔ TestNG & JUnit – Test automation frameworks.
Why It Matters?
These frameworks power large-scale software applications and automation testing.
Frequently Asked Questions (FAQ)
Q1: What is the best way to practice Core Java concepts? A: Work on small projects, participate in coding challenges, and contribute to open-source repositories.
Q2: How is Java used in Full Stack Software Testing? A: Java is used for writing test automation scripts, interacting with databases, and integrating test frameworks.
Q3: What is the difference between Checked and Unchecked Exceptions? A: Checked exceptions must be handled (e.g., IOException), whereas unchecked exceptions occur at runtime (e.g., NullPointerException).
Q4: Why is Java preferred for automation testing? A: Java offers robust libraries like Selenium, TestNG, and JUnit, making automation testing efficient and scalable.
Q5: What are the key Java concepts needed for API Testing? A: Understanding HTTP methods, JSON parsing, and REST API calls using libraries like RestAssured and Jackson is crucial.
Final Thoughts
Mastering Java fundamentals is the key to excelling in software development and automation testing. Whether you are preparing for a Full Stack Software Testing role in KPHB or looking to enhance your coding skills, these core Java concepts will set you apart.
#Java#CoreJava#FullStackTesting#SoftwareTesting#AutomationTesting#JavaProgramming#Selenium#TestAutomation#OOP#Coding#JavaDeveloper#JUnit#TestNG#FullStackDevelopment#KPHB#TechLearning
0 notes
Text
Understanding Design Patterns in Software Engineering
Design patterns play a crucial role in software engineering by offering reusable solutions to common problems encountered during development. They provide a standardized approach to designing software systems, making them more robust, maintainable, and scalable. This article explores the concept of design patterns, their types, and their significance in modern software engineering.
1. What Are Design Patterns?
Design patterns are proven templates or blueprints for solving recurring design problems in software development. They are not specific pieces of code but rather conceptual frameworks that guide developers in structuring their solutions effectively.
Key Characteristics:
Reusability: Promote code reuse across projects.
Scalability: Provide frameworks that adapt to growing requirements.
Best Practices: Reflect tried-and-tested solutions used by experienced developers.
Origin:
The concept of design patterns was popularized by the "Gang of Four" (GoF) in their book "Design Patterns: Elements of Reusable Object-Oriented Software" published in 1994.
2. Why Are Design Patterns Important?
Design patterns streamline the development process by:
Benefits:
Improving Code Readability: Standardized patterns make it easier for teams to understand and collaborate on code.
Facilitating Maintenance: Encouraging clean, modular design simplifies debugging and updates.
Encouraging Flexibility: Patterns promote loosely coupled code, enabling easier modifications and extensions.
Reducing Development Time: Leveraging existing patterns saves time compared to designing solutions from scratch.
3. Types of Design Patterns
Design patterns are broadly categorized into three types:
a. Creational Patterns
These patterns deal with object creation, ensuring flexibility and reuse.
Examples:
Singleton: Ensures a class has only one instance and provides a global access point.
Factory Method: Defines an interface for creating objects, allowing subclasses to alter the type of objects created.
Builder: Separates the construction of a complex object from its representation.
b. Structural Patterns
Structural patterns focus on class and object composition, ensuring the system’s components work together efficiently.
Examples:
Adapter: Allows incompatible interfaces to work together.
Decorator: Dynamically adds behavior to objects without modifying their code.
Composite: Composes objects into tree structures to represent part-whole hierarchies.
c. Behavioral Patterns
These patterns deal with communication and interaction between objects.
Examples:
Observer: Defines a one-to-many dependency between objects so that when one object changes state, all dependents are notified.
Strategy: Enables selecting an algorithm’s behavior at runtime.
Command: Encapsulates a request as an object, allowing parameterization of requests.
4. Commonly Used Design Patterns
a. Model-View-Controller (MVC)
Purpose: Separates an application into three interconnected components: Model, View, and Controller.
Use Cases: Web and mobile application development.
b. Dependency Injection (DI)
Purpose: Decouples object creation from its usage by injecting dependencies at runtime.
Use Cases: Frameworks like Spring and Angular.
c. Proxy Pattern
Purpose: Provides a placeholder or surrogate for another object to control access.
Use Cases: Lazy initialization, access control, and logging.
5. When to Use Design Patterns
Design patterns should be applied when:
A problem recurs frequently in your projects.
You need to ensure your code adheres to industry best practices.
Collaboration is necessary, and team members benefit from standardization.
Scalability and maintainability are critical for your application.
However, avoid overusing patterns where simpler solutions suffice, as this can lead to unnecessary complexity.
6. Challenges in Using Design Patterns
While beneficial, design patterns can present certain challenges:
Learning Curve: Understanding and applying patterns requires practice.
Overengineering: Improper use can lead to overly complex solutions.
Pattern Selection: Choosing the right pattern for a specific problem can be challenging.
7. Future of Design Patterns
With the rise of new technologies, design patterns continue to evolve:
AI and ML Integration: Patterns are being developed to optimize AI workflows and data pipelines.
Cloud Computing: Microservices architecture has led to new patterns like Circuit Breaker and API Gateway.
DevOps: Patterns like Infrastructure as Code (IaC) are gaining prominence in CI/CD pipelines.
Conclusion
Understanding design patterns is essential for software engineers aiming to write efficient, scalable, and maintainable code. By mastering these reusable templates, developers can tackle complex problems with confidence and consistency. While they require time and effort to learn, the long-term benefits in productivity and software quality make them invaluable. As technology continues to evolve, staying updated with emerging patterns will ensure that developers remain at the forefront of innovation.
1 note
·
View note
Text
) Explain the internal working of Spring Boot. Spring Boot works by automatically setting up default configurations based on the tools our project uses. It includes built-in servers like Tomcat to run our applications. Special starter packages make it easy to connect with other technologies. We can customize settings with simple annotations and properties files. The Spring Application class starts the app, and Spring Boot Actuator offers tools for monitoring and managing it
) How does a Spring application get started? A Spring application typically starts by initializing a Spring ApplicationContext, which manages the beans and dependencies. In Spring Boot, this is often triggered by calling SpringApplication.run() in the main method, which sets up the default configuration and starts the embedded server if necessary.
What is a Spring Bean? A Spring Bean is an object managed by the Spring framework. The framework creates, configures, and connects these beans for us, making it easier to manage dependencies and the lifecycle of objects.
Spring Boot dependency management makes it easier to handle the dependencies that our project depends on. Instead of manually keeping track of them, Spring Boot helps us manage them automatically
If a starter dependency includes conflicting versions of libraries with other dependencies, Spring Boot's dependency management resolves this by using a concept called "dependency resolution." It ensures that only one version of each library is included in the final application, prioritizing the most compatible version. This helps prevent runtime errors caused by conflicting dependencies and ensures the smooth functioning of the application
How to disable a specific auto-configuration class? We can disable specific auto-configuration classes in Spring Boot by using the exclude attribute of the @EnableAutoConfiguration annotation or by setting the spring.autoconfigure.exclude property in our application.properties or application.yml file.
Describe the flow of HTTPS requests through a Spring Boot application. In a Spring Boot application, HTTPS requests first pass through the embedded server's security layer, which manages SSL/TLS encryption. Then, the requests are routed to appropriate controllers based on URL mappings.
The @SpringBootApplication annotation is a convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations. It is used to mark the main class of a Spring Boot application and trigger auto-configuration and component scanning. On the other hand, @EnableAutoConfiguration specifically enables Spring Boot's auto-configuration mechanism, which attempts to automatically configure our application based on the jar dependencies we have added.
I would:
Use dependency injection to manage dependencies.
Utilize Spring Profiles for environment-specific configurations.
Group related beans in separate configuration classes.
Use @ComponentScan to automatically discover beans.
You have a singleton bean that needs to be thread-safe. What approaches would you take to ensure its thread safety? I would:
Use synchronized methods or blocks to control access to critical sections.
Use ThreadLocal to provide thread-confined objects.
Implement stateless beans where possible to avoid share
To enable Spring Boot Actuator, we simply add the spring-boot-starter-actuator dependency to our project’s build file. O
The dev-tools dependency in Spring Boot provides features that enhance the development experience. It enables automatic restarts of our application when code changes are detected, which is faster than restarting manually.
To test a Spring Boot application, we use different tools and annotations. For testing the whole application together, we use @SpringBootTest. When we want to test just a part of our application, like the web layer, we use @WebMvcTest
How do you handle exceptions in Spring Boot applications? In Spring Boot, I handle errors by creating a special class with @ControllerAdvice or @RestControllerAdvice. This class has methods marked with @ExceptionHandler that deal with different types of errors. These methods help make sure that when something goes wrong, my application responds in a helpful way, like sending a clear error message or a specific error code.
) How can you disable specific auto-configuration classes in Spring Boot? We can disable specific auto-configuration classes in Spring Boot by using the @SpringBootApplication annotation with the exclude attribute. For example, @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) will disable the DataSourceAutoConfiguration class.
Versioning in REST APIs helps manage changes without breaking existing clients. It allows different versions of the API to exist at the same time, making it easier for clients to upgrade gradually. We can version REST APIs in several ways: include the version number in the URL (e.g., /api/v1/resource), add a version parameter in the URL (e.g., /api/resource?version=1), use custom headers to specify the version (e.g., Accept: application/vnd.example.v1+json), or use media types for versioning (e.g., application/vnd.example.v1+json).
ResponseEntity in Spring Boot is used to customize responses. It lets us set HTTP status codes, add custom headers, and return response data as Java objects. This flexibility helps create detailed and informative responses. For example, new ResponseEntity<>("Hello, World!", HttpStatus.OK) sends back "Hello, World!" with a status code of 200 OK.
To disable the default server and enable a different one in Spring Boot, exclude the default server dependency in the pom.xml or build.gradle file and add the dependency for the desired server. For example, to switch from Tomcat to Jetty, exclude the Tomcat dependency and include the Jetty dependency in our project configuration.
@ComponentScan annotation in Spring tells the framework where to look for components, services, and configurations. It automatically discovers and registers beans in the specified packages, eliminating the need for manual bean registration and making it easier to manage and scale the application's architecture. EnableAutoConfiguration annotation in Spring Boot tells the framework to automatically configure our application based on the libraries we have included. This means Spring Boot can set up our project with the default settings that are most likely to work well for our setup.
EnableAsync annotation in Spring enables asynchronous method execution. It allows methods to run in the background on a separate thread, improving performance by freeing up the main thread for other tasks.
RestController annotation in Spring marks a class as a RESTful web service controller. It combines @Controller and @ResponseBody, meaning the methods in the class automatically return JSON or XML responses, making it easy to create REST APIs.
EnableScheduling is an annotation in Spring Framework used to enable scheduling capabilities for methods within a Spring application. It allows methods annotated with @Scheduled to be executed based on specified time intervals or cron expressions
0 notes
Text
Top Tools and Frameworks for Custom Software
In the world of tech, custom software is on the rise. Every business, big or small, wants software that’s made for them. But here’s the thing custom software isn’t just about writing code. It’s about choosing the right tools and frameworks that match your project goals, scale and performance. The tools you choose can make or break your project, from development speed to end user experience.
So whether you’re a developer, project manager or business owner looking to get the most out of your custom software development, knowing the top tools and frameworks out there is key. In this post we’ll look at some of the most popular and powerful ones that can help you bring your software to life.
1. React.js
React.js is the go to framework for front-end development. Built by Facebook, this JavaScript library lets you build dynamic and interactive UI’s with ease. Its component based architecture makes it perfect for large scale applications where consistency and performance is key.
2. Angular
Angular, maintained by Google, is another big player in front-end development. Unlike React, Angular is a full framework that comes with everything you need to build robust applications, from data binding to dependency injection. Its strong community support and regular updates means your application will always be modern and efficient.
3. Django
For back-end development, Django is a framework that’s hard to ignore. Written in Python, Django helps developers build secure and scalable web applications fast. Its “batteries-included” philosophy means it comes with loads of built-in features like authentication, ORM (Object-Relational Mapping) and more, so you don’t need to hunt for third party libraries.
4. Node.js
Node.js is a runtime environment that lets you run JavaScript on the server side. It’s popular for building scalable network applications thanks to its non-blocking, event driven architecture. Node.js is perfect for real-time applications like chat apps or online gaming where performance and speed is key.
5. Spring Boot
Spring Boot makes developing Java applications easier, especially when it comes to microservices. With its convention-over-configuration approach, Spring Boot reduces the amount of boilerplate code, so you can focus on the business logic of the app. It also plays nicely with other Spring components so it’s a great choice for enterprise apps.
6. Flutter
For mobile apps, Flutter is becoming a popular framework that lets you build natively compiled apps for mobile, web and desktop from a single codebase. Built by Google, Flutter’s UI approach using widgets lets you build fast and beautiful apps.
7. Docker
Not a framework, but a must have tool in modern software development. Docker lets you package your application into containers so the application will run the same way on your developer’s laptop as it will in production, so no more “it works on my machine” problem.
8. Kubernetes
As your software applications get more complex, managing them in production gets harder. This is where Kubernetes comes in. Kubernetes is an open source platform to automate deploying, scaling and operating application containers. It’s particularly useful for microservices architecture to ensure your application is resilient and scalable under different loads.
Summary
The world of custom software development is full of tools and frameworks, each with its own advantages. Choose the ones that fit your project’s needs. By using these tools you can speed up your development, improve your software and deliver what your business needs. Whether you want to build a front-end, back-end or high performance mobile app, there’s a tool or framework for that.
0 notes
Text
How to Maximize Enterprise Success with Java Solutions

Java has long been a stalwart in the world of enterprise solutions, powering a multitude of applications across various industries. With its platform-independent nature, strong community support, and a rich ecosystem of tools and libraries, Java Enterprise Solutions have become a go-to choice for businesses aiming to build robust and scalable software applications. In this article, we will explore the numerous advantages of using Java for enterprise-level development.
Platform Independence
One of Java’s most significant advantages is its platform independence. Java applications are compiled into bytecode, which can be executed on any platform with a Java Virtual Machine (JVM). This “write once, run anywhere” capability simplifies cross-platform compatibility, making it easier to develop applications that can work seamlessly on different operating systems. This platform independence is invaluable in enterprise environments with diverse hardware and software ecosystems.
Scalability
Enterprise applications often need to handle high traffic loads and accommodate growth over time. Java’s scalability is a key advantage in this regard. With technologies like Java EE (Enterprise Edition), developers can build applications that can be easily scaled horizontally by adding more servers or instances to handle increasing workloads. Java’s robust multithreading support also allows applications to make efficient use of multi-core processors, further enhancing scalability.
Strong Security
Security is paramount in enterprise software development, as sensitive data and transactions are at stake. Java provides a robust security model with features like the Security Manager, which allows developers to define fine-grained security policies for their applications. Additionally, Java’s extensive community and regular updates ensure that security vulnerabilities are quickly identified and patched.
Rich Ecosystem
Java boasts a vast ecosystem of libraries, frameworks, and tools that simplify and accelerate development. Popular frameworks like Spring and JavaServer Faces (JSF) provide pre-built components for common enterprise patterns, such as dependency injection and web application development. This ecosystem reduces development time and minimizes the need to reinvent the wheel, allowing developers to focus on building business logic.
Strong Community Support
The Java community is one of the largest and most active in the software development world. This vibrant community contributes to the continuous improvement of the language and its libraries. Developers can find answers to their questions, access tutorials, and collaborate with peers on open-source projects. This support network is invaluable for enterprise teams facing complex challenges.
Reliability and Stability
Enterprise applications need to be reliable and stable to ensure uninterrupted business operations. Java is renowned for its stability and backward compatibility. Applications written in older versions of Java can often run on newer JVMs without modification, reducing the risk of software obsolescence. Additionally, the extensive testing and quality assurance processes associated with Java contribute to the language’s reputation for reliability.
Portability
Java’s portability extends beyond just platform independence. It also allows for easy migration of applications between different environments, such as moving from on-premises servers to cloud-based infrastructure. This flexibility is crucial for enterprises looking to adapt to changing business needs and take advantage of evolving technology trends.
Performance
While Java is sometimes criticized for its performance compared to lower-level languages like C++, modern JVMs have made significant improvements in this area. With just-in-time (JIT) compilation and advanced runtime optimizations, Java applications can achieve impressive performance levels. In cases where performance is a critical concern, Java allows for native code integration through Java Native Interface (JNI), enabling developers to leverage native libraries when needed.
Enterprise-Level Database Access
Java provides excellent support for connecting to and working with relational databases. JDBC (Java Database Connectivity) is a widely-used API that enables seamless integration with various database management systems (DBMS). This allows developers to build robust, data-driven applications with ease, a fundamental requirement for many enterprise solutions.
Versatile Use Cases
Java Enterprise Solutions are not limited to a specific industry or application type. Java can be used to develop a wide range of applications, from web and mobile applications to large-scale enterprise systems, scientific computing, and more. This versatility makes Java a viable choice for organizations with diverse software needs.
Conclusion
Java Enterprise Solutions offer a multitude of advantages that make it an attractive choice for businesses seeking to develop robust, scalable, and secure software applications. With its platform independence, scalability, strong security features, rich ecosystem, and vibrant community support, Java continues to be a top choice for enterprise-level development. Its reliability, portability, and versatility further solidify its position as a dependable technology for addressing the complex challenges of the modern business world. As enterprises continue to evolve and innovate, Java remains a trusted partner in their software development journey.
0 notes
Text
A Beginner's Guide to Java Development

Welcome to the world of Java development! If you're aspiring to become a Full Stack Java Development service, you're on the right path. Java is a versatile and powerful programming language used in a wide range of applications, from web development to mobile apps and even in big data processing. In this beginner's guide, we'll walk you through the fundamentals of Java development, essential concepts, and the steps to embark on your journey to becoming a Full Stack Java Developer.
1. Getting Started with Java
Java is known for its "Write Once, Run Anywhere" philosophy, which means you can develop code on one platform and run it on any other platform that supports Java. To start your Java development journey, you'll need a few essential tools:
Java Development Kit (JDK): This includes the Java Runtime Environment (JRE) and the Java Compiler (javac). Download and install the latest version of JDK from the official Oracle website or an open-source alternative like OpenJDK.
Integrated Development Environment (IDE): An IDE simplifies the development process. Popular Java IDEs include Eclipse, IntelliJ IDEA, and NetBeans. Choose the one that suits your preferences.
Text Editor: If you prefer a lightweight approach, you can use a text editor like Visual Studio Code or Sublime Text with Java extensions.
Once you have these tools in place, you're ready to write and run Java code.
2. Understanding Java Basics
Before diving into Full Stack Java Development, you should have a solid grasp of the fundamental Java concepts:
Variables and Data Types: Java supports various data types, including int, double, char, and boolean. Variables hold data, and their types must be declared explicitly.
Control Flow: Learn how to use conditional statements (if-else), loops (for, while), and switch-case statements for decision-making in your programs.
Functions (Methods): In Java, functions are called methods. Understand how to define and call methods, pass parameters, and return values.
Classes and Objects: Object-oriented programming (OOP) is at the core of Java. Learn how to create classes, instantiate objects, and define class members like fields and methods.
3. Object-Oriented Programming (OOP)
Java's OOP principles are essential for becoming a proficient Full Stack Java Developer. OOP helps you structure your code in a way that is modular and easy to maintain. Key OOP concepts in Java include:
Encapsulation: Wrapping data (fields) and methods (functions) together within a class to restrict access and protect data integrity.
Inheritance: Creating new classes from existing ones to reuse code and establish a hierarchy of classes.
Polymorphism: The ability of objects to take on multiple forms. This allows you to write flexible and extensible code.
Abstraction: Simplifying complex systems by breaking them down into smaller, manageable components.
4. Java Libraries and Frameworks
Java's extensive standard library and third-party frameworks make development more efficient. As a Full Stack Java Developer, you'll encounter several libraries and frameworks, such as:
Spring Framework: A popular framework for building robust and scalable Java applications. It provides support for various aspects, including dependency injection and aspect-oriented programming.
Hibernate: An object-relational mapping (ORM) framework that simplifies database interactions by mapping Java objects to database tables.
Apache Struts: A framework for building web applications with Java EE. It follows the Model-View-Controller (MVC) architecture.
Explore these libraries and frameworks to streamline your Java development projects.
5. Full Stack Java Development
Becoming a Full Stack Java Developer means mastering both front-end and back-end development using Java technologies. Here's how you can start:
Front-End Development:
For front-end development, Java developers often use JavaServer Pages (JSP), JavaServer Faces (JSF), or Thymeleaf. These technologies allow you to create dynamic web pages with Java on the client side. Additionally, you'll need to learn HTML, CSS, and JavaScript for a well-rounded skill set.
Back-End Development:
The back-end development in Java typically involves creating server-side applications. Popular choices include Java Servlets, which handle HTTP requests, and Java Persistence API (JPA) for database interactions. You'll also need to work with databases such as MySQL, PostgreSQL, or Oracle.
Furthermore, a crucial aspect of Full Stack Java Development is understanding how to integrate the front-end and back-end seamlessly. This involves handling data transfer, user authentication, and maintaining a responsive user interface.
6. Building Your Portfolio
To become a Full Stack Java Developer, practical experience is invaluable. Create a portfolio of projects that demonstrate your skills and showcase your abilities to potential employers. Consider working on:
Web Applications: Develop web applications that incorporate front-end and back-end components. Showcase your ability to create interactive and responsive user interfaces.
Database Projects: Work on database-centric projects, such as building e-commerce websites or content management systems, to demonstrate your data handling capabilities.
API Development: Create RESTful APIs using Java to showcase your ability to build scalable and interoperable services.
Having a diverse portfolio not only strengthens your skills but also makes you a more attractive candidate to potential employers.
7. Staying Updated
The tech industry is constantly evolving, and Java development is no exception. Stay updated with the latest trends, libraries, and frameworks in the Java ecosystem. Join online communities, participate in forums, and follow influential Java developers on social media to keep your knowledge up to date.
8. Conclusion
Congratulations on taking the first steps towards becoming a Full Stack Java Developer! In this beginner's guide, we've covered the essentials of Java development, from setting up your development environment to mastering key concepts like OOP and exploring libraries and frameworks. Remember that practice and hands-on experience are crucial in your journey. Start small, build projects, and continuously expand your skills to become a proficient Full Stack Java Developer.
As you embark on your Java development journey, remember to stay curious, ask questions, and seek out resources to help you along the way. Becoming a Full Stack Java Developer is a rewarding path that offers a world of opportunities in the ever-growing field of software development.
#digitalmarketing#digitalmarketingagency#digitalmarketingcompany#java development company#java development solution
0 notes
Text

"Components of full-stack Java development"
Full-stack Java development involves working with both the front-end and back-end aspects of a web application. Here are the key components and technologies associated with full-stack Java development:
Front-End Technologies:
HTML/CSS: These are fundamental for creating the structure and styling of web pages.
JavaScript: Used for client-side scripting to enhance interactivity and create dynamic content.
Front-End Frameworks/Libraries: Java developers often use frameworks like Angular, React, or Vue.js to build robust and efficient user interfaces.
Back-End Technologies:
Java Programming Language: The core language for server-side development.
Java Virtual Machine (JVM): The runtime environment that executes Java bytecode.
Servlets and JSP (JavaServer Pages): Traditional Java-based technologies for building dynamic web applications.
Spring Framework: A comprehensive framework that provides a wide range of features, including dependency injection, MVC (Model-View-Controller) architecture, and data access.
Hibernate: An ORM (Object-Relational Mapping) framework for simplifying database interactions.
RESTful Web Services: Java developers often use frameworks like Spring Boot to build RESTful APIs for communication between the front-end and back-end.
Database:
Relational Databases: MySQL, PostgreSQL, Oracle, or other relational database management systems (RDBMS) are commonly used.
NoSQL Databases: MongoDB, Cassandra, or other NoSQL databases may be used for certain applications.
Build Tools:
Maven or Gradle: These tools are used for project management, build automation, and dependency management.
Version Control:
Git: Version control system for tracking changes in the codebase and collaborating with other developers.
Web Servers:
Apache Tomcat: A widely used servlet container for deploying Java web applications.
Jetty, WildFly, JBoss, or GlassFish: Alternative application servers that can be used based on project requirements.
API Documentation:
Swagger/OpenAPI: Tools for documenting and testing APIs, ensuring better communication between front-end and back-end teams.
Front-End Build Tools:
Webpack, Babel, npm: Tools for bundling, transpiling, and managing front-end dependencies.
Testing:
JUnit: A popular testing framework for Java.
Selenium: Used for automated testing of web applications.
Mockito: A mocking framework for unit testing.
Containerization and Orchestration:
Docker: Containerization tool for packaging applications and their dependencies.
Kubernetes: Orchestration tool for managing containerized applications in a distributed environment.
Security:
Spring Security: An extension of the Spring framework for handling security aspects in Java applications.
SSL/TLS: Secure communication over the web.
Continuous Integration/Continuous Deployment (CI/CD):
Jenkins, GitLab CI, or Travis CI: Tools for automating the building, testing, and deployment of applications.
A full-stack Java developer should be proficient in both front-end and back-end technologies, and they need to have a good understanding of the entire development stack to build end-to-end web applications effectively.
0 notes
Link
1. Introduction With Spring Framework it is very easy to make an optional dependency injection thanks to the annotation @Autowired(required=false) . In this way we get that if the bean that is being referenced is not defined, its value will be a null and we can act accordingly to, for example, provide a default value. import org.springframework.stereotypeorg.Service; import …
0 notes
Text
Is 2021 When Swift Programming Language Goes More Mainstream?

Apple debuted the Swift programming language in 2014, and it quickly grabbed the interest of developers everywhere. Over the past few years, it’s birthed a whole sub-industry of merchandise, Udemy classes, and even bespoke conferences dedicated to the language—not exactly surprising, when you consider how the language is becoming the best path for building macOS and iOS apps.
TIOBE’s latest ranking shows that Swift’s use is outpacing the aging language it is meant to replace, Objective-C. However, multiple programming-language rankings (including analyst firm Redmonk’s) show that Objective-C is managing to hold on, probably because there’s a lot of legacy code out there that must be maintained (shifting everything to Swift is a time- and money-consuming process that must be done carefully).
Earlier this year, the Swift.org open source team made several interesting announcements, including Windows support, better interoperability with C via Swift Systems, and the ability to utilize atomic operations in a codebase. Swift 5.3, the latest iteration of the language, was also retooled to compile faster.
Six years in, Swift hasn’t supplanted Objective-C as many expected it would. Is 2021 the year that this language finally breaks through in a more mainstream way? We asked some experts what they thought.
The Pros
Mohammad Azam, Lead Full Stack Immersive Web instructor at DigitalCrafts and an Udemy instructor, points out how Swift now has all the components of other major languages: “[Swift] consists of features like optionals, closures, optional function arguments, and protocols.”
It wasn’t always like that, and you can find some great accounts of how companies jumped quickly to embrace the first few versions, only to ram into unexpected difficulties. But now things are maturing. Paweł Kozielecki, iOS Tech Lead at Netguru, agrees with Azam that optionals “are a great programming concept, allowing you to not only prevent crashes, but also to enforce clean code across your application.”
Kozielecki says that Swift’s use of extensions is also important: “Extensions (initially known as Categories in Objective-C days) are a great way to add additional functionality to an object, without a necessity to extend it or build a wrapper around it. Categories add a set of methods or computable variables to a class in runtime (that is: after the class itself has been compiled).”
What is even more significant, Kozielecki adds, is how “protocols in Swift also can be extended (a.k.a. Protocol Extensions, also called default implementations for convenience). Such extensions can implement selected methods from the definition of a given protocol, greatly decreasing an amount of code a developer has to implement to conform to that protocol.”
Readability and frameworks are also key, according to Bear Cahill, Lead Mobile Developer and President at Brainwash and a Lynda instructor: “Both of these attributes help Swift to be highly maintainable. Also, the code can often be written with optimizations (e.g., shorthand argument labels), which allow for concise code.”
Last but certainly not least, a growing community is a huge plus, lending structure and support. But what’s Swift lacking, if anything? While many developers like to speculate freely about which features the Swift team should add, our panel points out that team may have already overlooked some features and tweaks that could have given the language a much more dominant footprint within Apple’s walled garden.
The Cons
Cahill points out Swift 5.3’s compile time fixes may be—well, timely: “While Swift allows for quick development using LLVM, redeploying changes as a new build in the simulator/device is a glaring speed bump.”
Azam suggests “Swift is a typed language, so it’s fast,” but Kozielecki isn’t sure that’s a net positive:
Compared to Kotlin or Java, Swift is not a reflective language (as it is statically typed). Swift offers a substitute – a Mirror functionality, but it is not the same. An object in Swift can “self-describe” (eg. get a list of its members) but cannot manipulate them from within. Through reflection, eg. it is easy to create Java classes mocks for testing, automatically inject dependencies, etc. It’d be a great feature in Swift, albeit very difficult to achieve.
Kozielecki goes on to note how the ABI architecture isn’t always reliable: “Despite the introduction of the Application Binary Interface in Swift 5.1, code compiled with different versions of Swift (eg. 5.1 and 5.2) often have problems working together. In the days of Objective-C, a piece of code could have been conveniently compiled into a static library, and easily introduced into a project as a dependency.”
In Swift, though, it wasn’t possible to produce static libraries until recently, which forced companies and developers to continue to use Objective-C if they didn’t want to expose their code.
Azam adds: “Sometimes the strictness of [Swift] may get in the way of your work.”
While Windows support is coming, and Linux support exists, Cahill points out that Swift still doesn’t reach the most core technology for many developers out there: the web. “Despite being open-source and cross-platform, Swift doesn’t have a well-known presence nor many supported IDEs,” Cahill says. “Being a compiled, versus interpreted, language may prevent it from being widely adopted in the web development community. Thus, it can suffer from an perception that it’s ‘an iOS/Mac/Apple language.’”
We can pontificate endlessly on how Apple/the Swift team may solve for ‘x’ in these instances. Maybe the WYSIWYG energy of SwiftUI is the front-end web developer tooling that will compliment work with back-end Linux environments. Perhaps Swift will soon branch out from Xcode and become more usable in other IDEs. Perhaps improvements to Async will kick the language into high gear.
Swift is an Apple-only language, even though it works with other platforms and environments. Apple is also one of the most dynamic tech companies around, and its next big bet will be augmented reality (AR). The company hints that AR will be the next big paradigm shift in mobile, and perhaps tech as we know it. If that holds true, Swift will become an incredibly important language (and its use will skyrocket). That said, 2021 likely won’t be the year of AR, and Swift still has too much work to do to spring into a truly dominant position… both in the Apple ecosystem and beyond.
Azper tech Inc is best web development company in Canada for programming work & website development
0 notes
Text
Robust Java Frameworks for Your Web App Development Projects!

Released on 23rd Jan 1996, Java is 24 years old now. Despite being in the market for more than two decades, it is extremely relevant even today and universally accepted programming language. Many Technology giants like Amazon, Netflix, eBay, IBM, Dell, Oracle, etc are widely using these frameworks. It has constantly ranked in the first position as per the TIOBE index.
It is possible to architect highly secure customer-centric apps using Java application development. Java is a robust and dynamic language and when combined with its frameworks, provides excellent solutions for diverse industrial domains like healthcare, eCommerce, transportation, finance, education, banking, etc.
In this blog, you will get a glimpse of the top Java frameworks used by Java developers along with their pros and cons. But, before we dive deeper into it, let’s quickly run through what Java frameworks are and why they are used? What are Java frameworks and why they are used? A Java framework is a body of pre-written code to enable easier, faster, and efficient development as well as the deployment of the web apps. It is a kind of template which the developers can use for Java web app development by adding their own code and re-using the components in it.
A Java framework alleviates the need to write the code from scratch. It gives a structure to the web apps by automating a lot of things for consistent and accurate results. These may even include predefined functions and classes for interacting with software systems or managing the hardware devices, depending upon the type of framework. One can use the framework by calling the inheritance, functions, providing call backs, listeners, etc. Promising Java Frameworks to Know in 2020! There are multiple frameworks available in the market for Java web app development and they all serve different purposes and good for specific requirements. Here are the most commonly used Java frameworks that you must know.

Spring
Spring is an open-source Java framework that is lightweight, powerful, and known for building complex and high-performing web apps. It is a feature-rich modular framework that has several add-ons like REST APIs, SOAP services, secured authentication, etc. The aspect-oriented programming features and the concept of dependency injection in spring allow the Java developers to develop enterprise-level applications. It is a framework having several modules like Spring Core, Spring Security, Spring ORM, Spring MVC, Spring Boost, Spring Transaction, etc. Pros
Supports JDBC thereby reducing the errors and enhancing the productivity
Better modularity for enhanced code readability
The Framework is lightweight, hence can be triggered without an application server
Supports XML as well as annotation-based configuration
Simplified injection to test data through POJOs
Supports Inversion of Control (IOC) to satisfy the application dependencies itself
Provides backward compatibility and testability of the code
Cons
Learning Spring could be time-consuming and difficult
A newbie may find it difficult to implement MVC
It keeps changing over time
Hibernate
Hibernate isn’t a full-stack framework but is one of the best frameworks when it comes to the database. It is an Object-Relational Mapping (ORM) framework used for building highly stable apps. ORM is useful in connecting data across incompatible systems and helps the data to flow seamlessly; thus making it easier to work in a complex ecosystem. It also helps to overcome issues like Paradigm Mismatch or Object-Relational Impedance Mismatch. Hibernate also facilitates sound communication between Relational Database Management Systems (RDBMS) and Java programming language. A Java application development company can rely on this framework for developing scalable web apps.
Pros
Free, open-source and powerful
Productivity, portability, scalability, and maintainability
With small modifications in code, communicating with any database is possible
Repetitive code is removed from the JDBC API
Cons
Restarting could be immensely slow at times
In the case of power-cut, all the data may be lost
Google Web Toolkit (GWT)
This is a free, open-source, and developer-friendly framework, that helps to build complex applications at a fast pace without the proficiency in front-end technologies. It is used for creating and debugging Ajax apps in Java. It allows conversion of Java code into JavaScript code which saves time and effort to a great extent. It provides great features such as bookmarking, internationalization, cross-browser compatibility, management of history, etc. GWT is one of the best frameworks for responsive and performant web apps with a lower load on server-side and heavy lifting on the client-side. Pros
Easy to learn
Google APIs can be used in apps built using GWT.
Reusability of code
Cons
Though it is evolving at a fast pace, all functions and interfaces may not be available.
Its compilation is slower and may require a proprietary method for defining structures.
Java Server Faces (JSF)
Developed by Oracle, JSF helps to build user interfaces for applications developed in Java. It is a framework based on the design pattern of MVC used for building native apps and enterprise apps. It is a stable framework. In this framework, User Interfaces can be created simply by drag and drop of the UI components. It has an architecture that differentiates between app logic and representation in an explicit manner.JSF may not be a very efficient framework but is easy to use due to the support of Oracle’s methodical documentation.
Pros
Offers outstanding tools and rich libraries
It has reusable UI components
This framework is an intrinsic part of Java EE
Developers using IDE software find this framework convenient to use.
Cons
Without prior experience in Java web app development, learning JSF would be quite hectic.
Grails
Grails is a full-stack dynamic framework. It uses Spring MVC as the base web application framework to develop applications based on the MVC design pattern. It is written in the programming language called Groovy and is much compatible with the syntax in Java. It works seamlessly with (JVM) and offers robust features like compile-time meta-programming, asynchronous programming, etc. Grails works with technologies like Java EE containers, SiteMesh, Spring, Hibernate, Quartz, etc.
Pros
The Setup process is much easier
Object mapping is easy
Provides a rapid development cycle
Has a variety of plug-ins for making the programming easier
Managing CSS is easy
Supports configuration which is dynamic
It has well-structured and easy documentation.
Cons
Working on multi-threaded apps could be tedious at times
Developers need to work with runtime language
Play
Mobile and Web Applications can be built using Scala and Java with the base as Play framework. It has an architecture that is lightweight and web-friendly. This framework is built on Akka and uses the asynchronous model designed on top of the Akka toolkit. As it is developed over Akka, it minimizes resource consumption like CPU, memory, etc, which facilitates in developing scalable applications. Pros
Asynchronous processing ensures high performance
It provides features like ‘hot reload’ and convention over configuration
It is a highly flexible framework known for failure-tolerant results
Typesafe and Zenexity provide commercial support to this framework
Improves productivity of the developer
Cons
Since it is developed over I/O a sync, Java developers will need to handle inner classes which would be difficult to identify
There isn’t much difference between Play1 and Play2
It may or may not follow J2EE web standards
End Note:
Every project has a specific requirement and so, choosing the right framework could be challenging. The frameworks mentioned above are the most widely used by almost every Java web app development company. All of them are designed to suit different project needs. By studying their significance, pros, and cons you can decide the best one for your project.
I hope this blog helps you to find the best-suited Java framework for your business requirements.
Let us know your comments on this.
For any other queries, drop us a mail at [email protected]!
0 notes
Text
300+ TOP Apache TAPESTRY Interview Questions and Answers
Apache Tapestry Interview Questions for freshers experienced :-
1. What is Apache Tapestry? It is an open source web framework written in Java and can work under any application server. It is easily integrate with back ends like Hibernate and Spring etc. It is a component based web framework. 2. What are the benefits of Apache Tapestry? Benefits of Apache Tapestry are: Adaptive API Fast framework Build-in Inversion Control Highly scalable web applications Storage management of Persistent state 3. What are the features of Apache Tapestry? Features of Apache Tapestry are: Live class reloading Code less, deliver more Static structure and dynamic behavior Detailed and clear exception reporting Extensive use of POJOs (Plain Old Java Objects) 4. Who is the developer of Apache tapestry? Apache Tapestry is developed by “Howard Lewis Ship”. 5. What is the component annotations used in Apache Tapestry? Component annotations used in Apache Tapestry are: @Log @Path @import @Property @Parameter @Environmental 6. What is IoC annotation? IoC annotation: It is used to inject objects into IoC Container. Type of IoC annotation are: @Value @Inject 7. What is CleanupRender? CleanupRender: It is used to release the objects created during rendering process. It is the counterpart of the SetupRender. 8. What is Two-way Data Binding? In Two-way data binding, we can communicate and transfer data with the use of parameters, components and its corresponding page. 9. What is Validate expansion? Validate expansion: It is a specialized string that is used to specify the validation rule of an object. 10. What is Form Component? It is used to create a form in the tapestry page for user input. A form can contain text fields, checkbox fields, date fields, submit button, select options and more.
Apache TAPESTRY Interview Questions 11. Does Apache Tapestry use JSP Tag libraries? No, It does not use JSP Tag library. 12. What is TextField Component? TextField Component: It is used to edit a single line of text. 13. What are the significant parameters used in Form Validation? Significant parameters used in Form Validation are: Min Max Email MaxDate MaxLength MinLength 14. What are the ways provided by Apache Tapestry to persist the data? There are two ways provided by Apache Tapestry to persist the data are: Session Storage Persistence page data 15. What is SSO? SSO stands for Session Store Object. It is a specialized store that is used to store complex / special object. Data types can also be stored using SSO. 16. Why Do We Need @script In Apache Tapestry? The script framework is an effective means to bundle scripts in components. It provides scripts with the advantages of components. It can now be reused like a component and not have to worry about renaming field names or the wiring between the fields and the scripts. You just declare the component and you are good to go. It certainly is another layer of abstraction that one will have to learn but once you have learned it, it is very powerful. And honestly there is not much to it. The script framework is mandated by the fact that form element/field names are automatically generated by the framework. And so you write your script in XML and use variables for these names and let the framework provide the correct names during runtime. Going further, you may also ask the framework to provide other objects that would help in creating your script. For example… This defines an input variable “select” of type “org.apache.tapestry.form.PropertySelection”. All such variables/symbols passed in to the script is stored in a symbol map. And now you can use the form select list name by using an ant style syntax like ${select.name}. The expression within “${}” is an OGNL expression and is evaluated with respect to the symbol map. You may also define your own symbols/variables using like… document.${select.form.name} ${formObj}.${select.name} These variables/symbols are stored in the symbol map also. So now if you want to set the value of the form select list all you do is say ${formObj}.${selectObj}.value = ‘whatever’; this would be equivalent to document.myForm.mySelect.value = ‘whatever’; where myForm is the form name and mySelect is the select list name. s are like method parameters and s are like instance variables. Typically you would pass values to the s via the Script component like... The actual scripts are defined in one of the two sections of the script specification, or , depending on when you want the script to execute. If you want the script to execute on load of the page, then you define it in the , if you want it to execute on any other event, define it in the section of the specification. For example… function onChangeList(listObj) { alert(listObj.value); } ${selectObj}.onchange = function(e) { onChangeList(${selectObj}); } As you can see in the rendered page all scripts are aggregated at the top of the page body, there are no more scripts all over the page. Even event handlers are attached to form objects in the initialization block. One more thing to remember, scripts being components, and components by nature being independent of its environment, will render the script in the page once for every ocurrance of the component. If you want the body of the script to be rendered only once no matter how many times the component is used, just wrap the body in a tag like… function onChangeList(listObj) { alert(listObj.value); } 17. What’s The Lifecycle Of A Form Submit? Events will trigger in the following order: initialize() pageBeginRender() formListenerMethod() pageBeginRender() The form “rewind” cycle is nothing more than a render cycle where the output is buffered and scrapped rather than written to the servlet output stream. The second pageBeginRender() is triggered during the actual page rendering. You can use requestCycle.isRewinding() to distinguish between these two render cycles. 18. Can I Use The Same Component Multiple Times In One Template? No – but you can copy the definition of a component pretty easily. 19. How Should Do Page Navigation In Apache Tapestry? Usage page properties: Page1.page Page2.page Welcome.Action.java public void submitListener(IRequestCycle cycle) { if (success) cycle.activate(getSpecification().getProperty("success")); if (error) cycle.activate(getSpecification().getProperty("error")); } So on success, it will be redirected to Home2 and on error it will be redirected to Error2 page. 20. Is Tapestry A Jsp Tag Library? Tapestry is not a JSP tag library; Tapestry builds on the servlet API, but doesn’t use JSPs in any way. It uses it own HTML template format and its own rendering engine. Starting with release 3.0, Tapestry includes a simple JSP tag library to allow JSP pages to create links to Tapestry pages. Apache TAPESTRY Questions and Answers Pdf Download Read the full article
0 notes
Text
Spring Interview Questions and Answers
Spring Interview Questions
What is Spring Framework?
What are some of the important features and advantages of Spring Framework?
What do you understand by Dependency Injection?
How do we implement DI in Spring Framework?
What are the new features in Spring 5?
What is Spring WebFlux?
What are the benefits of using Spring Tool Suite?
Name some of the important Spring Modules?
What do you understand by Aspect Oriented Programming?
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
What is the difference between Spring AOP and AspectJ AOP?
What is Spring IoC Container?
What is a Spring Bean?
What is the importance of Spring bean configuration file?
What are different ways to configure a class as Spring Bean?
What are different scopes of Spring Bean?
What is Spring Bean life cycle?
How to get ServletContext and ServletConfig object in a Spring Bean?
What is Bean wiring and @Autowired annotation?
What are different types of Spring Bean autowiring?
Does Spring Bean provide thread safety?
What is a Controller in Spring MVC?
What’s the difference between @Component, @Repository & @Service annotations in Spring?
What is DispatcherServlet and ContextLoaderListener?
What is ViewResolver in Spring?
What is a MultipartResolver and when it’s used?
How to handle exceptions in Spring MVC Framework?
How to create ApplicationContext in a Java Program?
Can we have multiple Spring configuration files?
What is ContextLoaderListener?
What are the minimum configurations needed to create Spring MVC application?
How would you relate Spring MVC Framework to MVC architecture?
How to achieve localization in Spring MVC applications?
How can we use Spring to create Restful Web Service returning JSON response?
What are some of the important Spring annotations you have used?
Can we send an Object as the response of Controller handler method?
How to upload file in Spring MVC Application?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
What is Spring JdbcTemplate class and how to use it?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you achieve Transaction Management in Spring?
What is Spring DAO?
How to integrate Spring and Hibernate Frameworks?
What is Spring Security?
How to inject a java.util.Properties into a Spring Bean?
Name some of the design patterns used in Spring Framework?
What are some of the best practices for Spring Framework?
Spring Interview Questions and Answers
Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.
Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross-cutting tasks such as logging and authentication using spring support for aspect-oriented programming.
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with the Spring framework is easy and fun at the same time.
Recommended Read: Spring Framework
Spring Framework is built on top of two design concepts �� Dependency Injection and Aspect Oriented Programming.
Some of the features of spring framework are:
Lightweight and very little overhead of using framework for our development.
Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency on our project.
Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example, there is a Spring project for Android to help us write better code for native Android applications. This makes spring framework a complete package and we don’t need to look after the different framework for different requirements.
Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are Separation of Concerns, Boilerplate Code reduction, Configurable components, and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injection to automate the process of dependency injection. But in most of the cases, we are looking for more than just dependency injection and that’s why Spring is the top choice for this.
We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains a sample project zip file, that you can download and play around to learn more.
Spring 5 brought a massive update to Spring framework. Some of the new features in Spring 5 are:
Spring 5 runs on Java 8+ and supports Java EE 7. So we can use lambda expressions and Servlet 4.0 features. It’s good to see Spring trying to support the latest versions.
Spring Framework 5.0 comes with its own Commons Logging bridge; spring-jcl instead of standard Commons Logging.
Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
Spring WebFlux brings reactive programming to the Spring Framework.
Spring 5 also supports Kotlin programming now. This is a huge step towards supporting functional programming, just as Java is also moving towards functional programming.
Support for JUnit 5 and parallel testing execution in the Spring TestContext Framework.
You can read about these features in more detail at Spring 5 Features.
Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in spring framework.
Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.
You can read more about it at Spring WebFlux Tutorial.
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring-based applications.
Some of the important Spring Framework modules are:
Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that are not possible in normal object-oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.
Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.
AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
One of the shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and makes it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.
We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean XML file and initializes all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.
There are three different ways to configure Spring Bean.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
<bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
@Configuration @ComponentScan(value="com.journaldev.spring.main") public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } }
To get this bean from spring context, we need to use following code snippet:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( MyConfiguration.class); MyService service = ctx.getBean(MyService.class);
<context:component-scan base-package="com.journaldev.spring" />
There are five scopes defined for Spring Beans.
singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.
To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the context is destroyed, it also destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
We can do this by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle Methods.
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
@Autowired ServletContext servletContext;
The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually, it’s best practice to do the explicit wiring of all the bean dependencies, but the spring framework also supports auto-wiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation-based configuration in spring bean configuration file. This can be done by context:annotation-config element.
For more details about @Autowired annotation, please read Spring Autowire Example.
There are four types of autowiring in Spring framework.
autowire byName
autowire byType
autowire by constructor
autowiring by @Autowired and @Qualifier annotations
Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType. For more details about these options, please read Spring Bean Autowiring.
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
However, we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle a different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually, it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.
@Component is used to indicate that a class is a component. These classes are used for auto-detection and configured as bean when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually, the business facade classes that provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean>
InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please read Spring MVC File Upload Example.
Spring MVC Framework provides the following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
For a complete example, please read Spring Exception Handling Example.
There are following ways to create spring context in a standalone java program.
AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
We can also define multiple root level spring configurations and load it through context-param. For example;
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value> </context-param>
Another option is to use import element in the context configuration file to import other configurations, for example:
<beans:import resource="spring-jdbc.xml"/>
ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file as:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
For creating a simple Spring MVC application, we would need to do the following tasks.
Add spring-context and spring-webmvc dependencies in the project.
Configure DispatcherServlet in the web.xml file to handle requests through spring container.
Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC Hello World application.
As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.
The model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="classpath:messages" /> <beans:property name="defaultEncoding" value="UTF-8" /> </beans:bean> <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <beans:property name="defaultLocale" value="en" /> <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property> <beans:property name="cookieMaxAge" value="3600"></beans:property> </beans:bean> <interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <beans:property name="paramName" value="locale" /> </beans:bean> </interceptors>
For a complete example, please read Spring Localization Example.
We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.
We would need to do following steps to configure our Spring MVC application to send JSON response:
Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:
Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:
You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.
<!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind-version}</version> </dependency>
<!-- Configure to plugin JSON as request and response in method handler --> <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <beans:property name="messageConverters"> <beans:list> <beans:ref bean="jsonMessageConverter"/> </beans:list> </beans:property> </beans:bean> <!-- Configure bean to convert JSON to POJO and vice versa --> <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </beans:bean>
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET) public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) { logger.info("Start getEmployee. ID="+empId); return empData.get(empId); }
For a complete example, please read Spring Restful Webservice Example.
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it. For a complete example, please refer Spring File Upload Example.
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
For custom validator implementation, we need to configure it in the controller class. For a complete example, please read Spring MVC Form Validation Example.
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too. For a detailed example, please refer Spring MVC Interceptor Example.
Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
For JdbcTemplate example, please refer Spring JDBC Example.
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
Sample configuration would be:
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean>
For complete example, please refer Spring Tomcat JNDI Example.
Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure the transaction manager for the DataSource in the spring bean configuration file.
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.
Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for Hibernate boiler-plate code for transaction management.
For better understanding you should go through following tutorials:
Spring Hibernate Integration Example
Spring MVC Hibernate Integration Example
Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.
It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through the following posts to learn how to use the Spring Security framework.
Spring Security in Servlet Web Application
Spring MVC and Spring Security Integration Example
We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies. For example;
<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="location" value="/WEB-INF/application.properties" /> </bean> <bean class="com.journaldev.spring.EmployeeDaoImpl"> <property name="maxReadResults" value="${results.read.max}"/> </bean>
If you are using annotation to configure the spring bean, then you can inject property like below.
@Value("${maxReadResults}") private int maxReadResults;
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
Some of the best practices for Spring Framework are:
Avoid version numbers in schema reference, to make sure we have the latest configs.
Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
For smaller applications, annotations are useful but for larger applications, annotations can become a pain. If we have all the configuration in XML files, maintaining it will be easier.
Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
That’s all for Spring Framework interview questions. I hope these questions will help you in coming Java EE interview. I will keep on adding more questions to the list as soon as I found them. If you know some more questions that should be part of the list, make sure to add a comment for it and I will include it
0 notes
Link
(Via: Hacker News)
Today’s developers are expected to develop resilient and scalable distributed systems. Systems that are easy to patch in the face of security concerns and easy to do low-risk incremental upgrades. Systems that benefit from software reuse and innovation of the open source model. Achieving all of this for different languages, using a variety of application frameworks with embedded libraries is not possible.
Recently I’ve blogged about “Multi-Runtime Microservices Architecture” where I have explored the needs of distributed systems such as lifecycle management, advanced networking, resource binding, state abstraction and how these abstractions have been changing over the years. I also spoke about “The Evolution of Distributed Systems on Kubernetes” covering how Kubernetes Operators and the sidecar model are acting as the primary innovation mechanisms for delivering the same distributed system primitives.
On both occasions, the main takeaway is the prediction that the progression of software application architectures on Kubernetes moves towards the sidecar model managed by operators. Sidecars and operators could become a mainstream software distribution and consumption model and in some cases even replace software libraries and frameworks as we are used to.
The sidecar model allows the composition of applications written in different languages to deliver joint value, faster and without the runtime coupling. Let’s see a few concrete examples of sidecars and operators, and then we will explore how this new software composition paradigm could impact us.
Out-of-Process Smarts on the Rise
In Kubernetes, a sidecar is one of the core design patterns achieved easily by organizing multiple containers in a single Pod. The Pod construct ensures that the containers are always placed on the same node and can cooperate by interacting over networking, file system or other IPC methods. And operators allow the automation, management and integration of the sidecars with the rest of the platform. The sidecars represent a language-agnostic, scalable data plane offering distributed primitives to custom applications. And the operators represent their centralized management and control plane.
Let’s look at a few popular manifestations of the sidecar model.
Envoy
Service Meshes such as Istio, Consul, and others are using transparent service proxies such as Envoy for delivering enhanced networking capabilities for distributed systems. Envoy can improve security, it enables advanced traffic management, improves resilience, adds deep monitoring and tracing features. Not only that, it understands more and more Layer 7 protocols such as Redis, MongoDB, MySQL and most recently Kafka. It also added response caching capabilities and even WebAssembly support that will enable all kinds of custom plugins. Envoy is an example of how a transparent service proxy adds advanced networking capabilities to a distributed system without including them into the runtime of the distributed application components.
Skupper
In addition to the typical service mesh, there are also projects, such as Skupper, that ship application networking capabilities through an external agent. Skupper solves multicluster Kubernetes communication challenges through a Layer 7 virtual network and offers advanced routing and connectivity capabilities. But rather than embedding Skupper into the business service runtime, it runs an instance per Kubernetes namespace which acts as a shared sidecar.
Cloudstate
Cloudstate is another example of the sidecar model, but this time for providing stateful abstractions for the serverless development model. It offers stateful primitives over GRPC for EventSourcing, CQRS, Pub/Sub, Key/Value stores and other use cases. Again, it an example of sidecars and operators in action but this time for the serverless programming model.
Dapr
Dapr is a relatively young project started by Microsoft, and it is also using the sidecar model for providing developer-focused distributed system primitives. Dapr offers abstractions for state management, service invocation and fault handling, resource bindings, pub/sub, distributed tracing and others. Even though there is some overlap in the capabilities provided by Dapr and Service Mesh, both are very different in nature. Envoy with Istio is injected and runs transparently from the service and represents an operational tool. Dapr, on the other hand, has to be called explicitly from the application runtime over HTTP or gRPC and it is an explicit sidecar targeted for developers. It is a library for distributed primitives that is distributed and consumed as a sidecar, a model that may become very attractive for developers consuming distributed capabilities.
Camel K
Apache Camel is a mature integration library that rediscovers itself on Kubernetes. Its subproject Camel K uses heavily the operator model to improve the developer experience and integrate deeply with the Kubernetes platform. While Camel K does not rely on a sidecar, through its CLI and operator it is able to reuse the same application container and execute any local code modification in a remote Kubernetes cluster in less than a second. This is another example of developer-targeted software consumption through the operator model.
More to Come
And these are only some of the pioneer projects exploring various approaches through sidecars and operators. There is more work being done to reduce the networking overhead introduced by container-based distributed architectures such as the data plane development kit (DPDK), which is a userspace application that bypasses the layers of the Linux kernel networking stack and access directly to the network hardware. There is work in the Kubernetes project to create sidecar containers with more granular lifecycle guarantees. There are new Java projects based on GraalVM implementation such as Quarkus that reduce the resource consumption and application startup time which makes more workloads attractive for sidecars. All of these innovations will make the side-car model more attractive and enable the creation of even more such projects.
Sidecars providing distributed systems primitives
I’d not be surprised to see projects coming up around more specific use cases such as stateful orchestration of long-running processes such as Business Process Model and Notation (BPMN) engines in sidecars. Job schedulers in sidecars. Stateless integration engines i.e. Enterprise Integration Patterns implementations in sidecars. Data abstractions and data federation engines in sidecars. OAuth2/OpenID proxy in sidecars. Scalable database connection pools for serverless workloads in sidecars. Application networks as sidecars, etc. But why would software vendors and developers switch to this model? Let’s see a few of the benefits it provides.
Runtimes with Control Planes over Libraries
If you are a software vendor today, probably you have already considered offering your software to potential users as an API or a SaaS-based solution. This is the fastest software consumption model and a no-brainer to offer, when possible. Depending on the nature of the software you may be also distributing your software as a library or a runtime framework. Maybe it is time to consider if it can be offered as a container with an operator too. This mechanism of distributing software and the resulting architecture has some very unique benefits that the library mechanism cannot offer.
Supporting Polyglot Consumers
By offering libraries to be consumable through open protocols and standards, you open them up for all programming languages. A library that runs as a sidecar and consumable over HTTP, using a text format such as JSON does not require any specific client runtime library. Even when gRPC and Protobuf are used for low-latency and high-performance interactions, it is still easier to generate such clients than including third party custom libraries in the application runtime and implement certain interfaces.
Application Architecture Agnostic
The explicit sidecar architecture (as opposed to the transparent one) is a way of software capability consumption as a separate runtime behind a developer-focused API. It is an orthogonal feature that can be added to any application whether that is monolithic, microservices, functions-based, actor-based or anything in between. It can sit next to a monolith in a less dynamic environment, or next to every microservice in a dynamic cloud-based environment. It is trivial to create sidecars on Kubernetes, and doable on many other software orchestration platforms too.
Tolerant to Release Impedance Mismatch
Business logic is always custom and developed in house. Distributed system primitives are well-known commodity features, and consumed off-the-shelf as either platform features or runtime libraries. You might be consuming software for state abstractions, messaging clients, networking resiliency and monitoring libraries, etc. from third-party open source projects or companies. And these third party entities have their release cycles, critical fixes, CVE patches that impact your software release cycles too. When third party libraries are consumed as a separate runtime (sidecar), the upgrade process is simpler as it is behind an API and it is not coupled with your application runtime. The release impedance mismatch between your team and the consumed 3rd party libraries vendors becomes easier to manage.
Control Plane Included Mentality
When a feature is consumed as a library, it is included in your application runtime and it becomes your responsibility to understand how it works, how to configure, monitor, tune and upgrade. That is because the language runtimes (such as the JVM) and the runtime frameworks (such as Spring Boot or application servers) dictate how a third-party library can be included, configured, monitored and upgraded. When a software capability is consumed as a separate runtime (such as a sidecar or standalone container) it comes with its own control plane in the form of a Kubernetes operator.
That has a lot of benefits as the control plane understands the software it manages (the operand) and comes with all the necessary management intelligence that otherwise would be distributed as documentation and best practices. What’s more, operators also integrate deeply with Kubernetes and offer a unique blend of platform integration and operand management intelligence out-of-the-box. Operators are created by the same developers who are creating the operands, they understand the internals of the containerized features and know how to operate the best. Operators are executables SREs in containers, and the number of operators and their capabilities are increasing steadily with more operators and marketplaces coming up.
Software Distribution and Consumption in the Future
Software Distributed as Sidecars with Control Planes
Let’s say you are a software provider of a Java framework. You may distribute it as an archive or a Maven artifact. Maybe you have gone a step further and you distribute a container image. In either case, in today’s cloud-native world, that is not good enough. The users still have to know how to patch and upgrade a running application with zero downtime. They have to know what to backup and restore its state. They have to know how to configure their monitoring and alerting thresholds. They have to know how to detect and recover from complex failures. They have to know how to tune an application based on the current load profile.
In all of these and similar scenarios, intelligent control planes in the form of Kubernetes operators are the answer. An operator encapsulates platform and domain knowledge of an application in a declaratively configured component to manage the workload.
Sidecars and operators could become a mainstream software distribution and consumption model and in some cases even replace software libraries and frameworks as we are used to.
Let’s assume that you are providing a software library that is included in the consumer applications as a dependency. Maybe it is the client-side library of the backend framework described above. If it is in Java, for example, you may have certified it to run it on a JEE server, provided Spring Boot Starters, Builders, Factories, and other implementations that are all hidden behind a clean Java interface. You may have even backported it to .Net too.
With Kubernetes operators and sidecars all of that is hidden from the consumer. The factory classes are replaced by the operator, and the only configuration interface is a YAML file for the custom resource. The operator is then responsible for configuring the software and the platform so that users can consume it as an explicit sidecar, or a transparent proxy. In all cases, your application is available for consumption over remote API and fully integrated with the platform features and even other dependent operators. Let’s see how that happens.
Software Consumed over Remote APIs Rather than Embedded Libraries
One way to think about sidecars is similar to the composition over inheritance principle in OOP, but in a polyglot context. It is a different way of organizing the application responsibilities by composing capabilities from different processes rather than including them into a single application runtime as dependencies. When you consume software as a library, you instantiate a class, call its methods by passing some value objects. When you consume it as an out-of-process capability, you access a local process. In this model, methods are replaced with APIs, in-process methods invocation with HTTP or gRPC invocations, and value objects with something like CloudEvents. This is a change from application servers to Kubernetes as the distributed runtime. A change from language-specific interfaces, to remote APIs. From in-memory calls to HTTP, from value objects to CloudEvents, etc.
This requires software providers to distribute containers and controllers to operate them. To create IDEs that are capable of building and debugging multiple runtime services locally. CLIs for quickly deploying code changes into Kubernetes and configuring the control planes. Compilers that can decide what to compile in a custom application runtime, what capabilities to consume from a sidecar and what from the orchestration platform.
Software consumers and providers ecosystem
In the longer term, this will lead to the consolidation of standardized APIs that are used for the consumption of common primitives in sidecars. Rather than language-specific standards and APIs we will have polyglot APIs. For example, rather than Java Database Connectivity (JDBC) API, caching API for Java (JCache), Java Persistence API (JPA), we will have polyglot APIs over HTTP using something like CloudEvents. Sidecar centric APIs for messaging, caching, reliable networking, cron jobs and timer scheduling, resource bindings (connectors to other APIs, protocols), idempotency, SAGAs, etc. And all of these capabilities will be delivered with the management layer included in the form of operators and even wrapped with self-service UIs. The operators are key enablers here as they will make this even more distributed architecture easy to manage and self-operate on Kubernetes. The management interface of the operator is defined by the CustomResourceDefinition and represents another public-facing API that remains application-specific.
This is a big shift in mentality to a different way of distributing and consuming software, driven by the speed of delivery and operability. It is a shift from a single runtime to multi runtime application architectures. It is a shift similar to what the hardware industry had to go through from single-core to multicore platforms when Moore’s law ended. It is a shift that is slowly happening by building all the elements of the puzzle: we have uniformly adopted and standardized containers, we have a de facto standard for orchestration through Kubernetes, possibly improved sidecars coming soon, rapid operators adoption, CloudEvents as a widely agreed standard, light runtimes such as Quarkus, etc. With the foundation in place, applications, productivity tools, practices, standardized APIs, and ecosystem will come too.
This post was originally published at The New Stack here.
0 notes
Quote
Quarkus is a new technology aimed at cloud development. With Quarkus, you can take advantage of smaller runtimes optimized for the cloud. You don’t need to relearn new APIs. Quarkus is built on top of the best-of-breed technologies from the last decade, like Hibernate, RESTEasy, Vert.x, and MicroProfile. Quarkus is productive from day one. Quarkus is production ready. Quarkus created quite a buzz in the enterprise Java ecosystem in 2019. Like all other developers, I was curious about this new technology and saw a lot of potential in it. What exactly is Quarkus? How is it different from other technologies established in the market? How can Quarkus help me or my organization? Let’s find out. What is Quarkus? The Quarkus project dubbed itself Supersonic Subatomic Java. Is this actually real? What does this mean? To better explain the motivation behind the Quarkus project, we need to look into the current state of software development. From On-Premises to Cloud The old way to deploy applications was to use physical hardware. With the purchase of a physical box, we paid upfront for the hardware requirements. We had already made the investment, so it wouldn’t matter if we used all the machine resources or just a small amount. In most cases, we wouldn’t care that much as long as we could run the application. However, the Cloud is now changing the way we develop and deploy applications. In the Cloud, we pay exactly for what we use. So we have become pickier with our hardware usage. If the application takes 10 seconds to start, we have to pay for these 10 seconds even if the application is not yet ready for others to consume. Java and the Cloud Do you remember when the first Java version was released? Allow me to refresh your memory — it was in 1996. There was no Cloud back then. In fact, it only came into existence several years later. Java was definitely not tailored for this new paradigm and had to adjust. But how could we change a paradigm after so many years tied to a physical box where costs didn’t matter as much as they do in the Cloud? It’s All About the Runtime The way that many Java libraries and frameworks evolved over the years was to perform a set of enhancements during runtime. This was a convenient way to add capabilities to your code in a safe and declarative way. Do you need dependency injection? Sure! Use annotations. Do you need a transaction? Of course! Use an annotation. In fact, you can code a lot of things by using these annotations that the runtime will pick and handle for you. But there is always a catch. The runtime requires a scan of your classpath and classes for metadata. This is an expensive operation that consumes time and memory. Quarkus Paradigm Shift Quarkus addressed this challenge by moving expensive operations like Bytecode Enhancement, Dynamic ClassLoading, Proxying, and more to compile time. The result is an environment that consumes less memory, less CPU, and faster startup. This is perfect for the use case of the Cloud, but also useful for other use cases. Everyone will benefit from less resources consumption overall, no matter the environment. Maybe Quarkus is Not So New Have you heard of or used technologies such as CDI, JAX-RS, or JPA? If so, the Quarkus stack is composed of these technologies that have been around for several years. If you know how to develop these technologies, then you will know how to develop a Quarkus application. Do you recognize the following code? @Path("books") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) public class BookApi { @Inject BookRepository bookRepository; @GET @Path("/{id}") Response get(@PathParam("id")Long id) { return bookRepository.find(id) .map(Response::ok) .orElse(Response.status(NOT_FOUND)) .build(); } } Congratulations, you have your first Quarkus app! Best of Breed Frameworks and Standards The Quarkus programming model is built on top of proven standards, be it official standards or de facto standards. Right now, Quarkus has first class support for technologies like Hibernate, CDI, Eclipse MicroProfile, Kafka, Camel, Vert.x, Spring, Flyway, Kubernetes, Vault, just to name a few. When you adopt Quarkus, you will be productive from day one since you don’t really need to learn new technologies. You just use what has been out there for the past 10 years. Are you looking to use a library that isn’t yet in the Quarkus ecosystem? There is a good chance that it will work out of the box without any additional setup, unless you want to run it in GraalVM Native mode. If you want to go one step further, you could easily implement your own Quarkus extension to provide support for a particular technology and enrich the Quarkus ecosystem. Quarkus Setup So, you may be asking if there is something hiding under the covers. In fact yes there is. You are required to use a specific set of dependencies in your project that are provided by Quarkus. Don’t worry, Quarkus supports both Maven and Gradle. For convenience, you can generate a skeleton project in Quarkus starter page, and select which technologies you would like to use. Just import it in your favorite IDE and you are ready to go. Here is a sample Maven project to use JAX-RS with RESTEasy and JPA with Hibernate: 4.0.0 org.acme code-with-quarkus 1.0.0-SNAPSHOT 3.8.1 true 1.8 1.8 UTF-8 UTF-8 1.3.0.Final quarkus-universe-bom io.quarkus 1.3.0.Final 2.22.1 ${quarkus.platform.group-id} ${quarkus.platform.artifact-id} ${quarkus.platform.version} pom import io.quarkus quarkus-resteasy io.quarkus quarkus-junit5 test io.rest-assured rest-assured test io.quarkus quarkus-hibernate-orm io.quarkus quarkus-resteasy-jsonb io.quarkus quarkus-maven-plugin ${quarkus-plugin.version} build maven-compiler-plugin ${compiler-plugin.version} maven-surefire-plugin ${surefire-plugin.version} org.jboss.logmanager.LogManager You might have noticed that most of the dependencies start with the groupId io.quarkus and that they are not the usual dependencies that you might find for Hibernate, Resteasy, or Junit. Quarkus Dependencies Now, you may be wondering why Quarkus supplies their own wrapper versions around these popular libraries. The reason is to provide a bridge between the library and Quarkus to resolve the runtime dependencies at compile time. This is where the magic of Quarkus happens and provides projects with fast start times and smaller memory footprints. Does this mean that you are constrained to use only Quarkus specific libraries? Absolutely not. You can use any library you wish. You run Quarkus applications on the JVM as usual, where you don’t have limitations. GraalVM and Native Images Perhaps you already heard about this project called GraalVM by Oracle Labs? In essence, GraalVM is a Universal Virtual Machine to run applications in multiple languages. One of the most interesting features is the ability to build your application in a Native Image and run it even faster! In practice, this means that you just have an executable to run with all the required dependencies of your application resolved at compile time. This does not run on the JVM — it is a plain executable binary file, but includes all necessary components like memory management and thread scheduling from a different virtual machine, called Substrate VM to run your application. For convenience, the sample Maven project already has the required setup to build your project as native. You do need to have GraalVM in your system with the native-image tool installed. Follow these instructions on how to do so. After that, just build as any other Maven project but with the native profile: mvn verify -Pnative. This will generate a binary runner in the target folder, that you can run as any other binary, with ./project-name-runner. The following is a sample output of the runner in my box: [io.quarkus] (main) code-with-quarkus 1.0.0-SNAPSHOT (powered by Quarkus 1.3.0.Final) started in 0.023s. Listening on: http://0.0.0.0:8080 INFO [io.quarkus] (main) Profile prod activated. [io.quarkus] (main) Installed features: [agroal, cdi, hibernate-orm, narayana-jta, resteasy, resteasy-jsonb] Did you notice the startup time? Only 0.023s. Yes, our application doesn’t have much, but still pretty impressive. Even for real applications, you will see startup times in the order of milliseconds. You can learn more about GraalVM on their website. Developer Productivity We have seen that Quarkus could help your company become Cloud Native. Awesome. But what about the developer? We all like new shiny things, and we are also super lazy. What does Quarkus do for the developer that cannot be done with other technologies? Well, how about hot reloading that actually works without using external tools or complicated tricks? Yes, it is true. After 25 years, since Java was born, we now have a reliable way to change our code and see those changes with a simple refresh. Again, this is accomplished by the way Quarkus works internally. Everything is just code, so you don’t have to worry about the things that made hot reloading difficult anymore. It is a trivial operation. To accomplish this, you have to run Quarkus in Development Mode. Just run mvn quarkus:dev and you are good to go. Quarkus will start up and you are free to do the changes to your code and immediately see them. For instance, you can change your REST endpoint parameters, add new methods, and change paths. Once you invoke them, they will be updated reflecting your code changes. How cool is that? Is Quarkus Production Ready? All of this seems to be too good to be true, but is Quakus actually ready for production environments? Yes it is. A lot of companies are already adopting Quarkus as their development/runtime environment. Quarkus has a very fast release cadence (every few weeks), and a strong Open Source community that helps every developer in the Java community, whether they are just getting started with Quarkus or are an advanced user. Check out this sample application that you can download or clone. You can also read some of the adoption stories in a few blog posts so you can have a better idea of user experiences when using Quarkus. Conclusion After a year of its official announcement, Quarkus is already on version 1.3.1.Final. A lot of effort is being put in the project to help companies and developers to write applications that they can run natively in the Cloud. We don’t know how far Quarkus can go, but one thing is for certain: Quarkus shook the entire Java ecosystem in a space dominated by Spring. I think the Java ecosystem can only win by having multiple offerings that can push each other and innovate to keep themselves competitives.
http://damianfallon.blogspot.com/2020/04/getting-started-with-quarkus.html
0 notes
Text
Implement feature switches with spring
A feature toggle is a technique in software development that attempts to provide an alternative to maintaining multiple branches in source code, such that a software feature can be tested even before it is completed and ready for release. Feature toggle is used to hide, enable or disable the feature during runtime.
It often happens in our code that we need to provide extra calls to a function or an external system based on certain coditions. These conditions can be: * when a system property is set * depending on the environment we are in * on a condition in a parameter of a request
The code then becomes bloated with constructs like:
if (feature.isActive()) callExternalSystem();
if (object.isOfType()) doSomething(object); else doSomethingElse(object);
if (env == Env.DEMO) doSomething(object);
This complexifies the code and is not easy to maintain.
... comes the strategy pattern!
Strategy pattern
We'll implement a feature to scan files only when this feature is turned on. We'll use the document repository as an exmple.
@Service public class VirusScanService { @Overide boolean scan(byte[] toScan) { // scan the data for mischievous content return false; } }
And the service - DocumentService - that calls our virus scan:
@Autorwired private MetadataRepository metadataRepository; @Autorwired private VirusScanService virusScanService; @Autorwired private FileRepository fileRepository; @Transactional public uploadDocument(Metadata metadata, byte[] data) { String documentId = metadataRepository.save(metadata); virusScanService.scan(data); fileRepository.save(documentId, data); }
In this example, the virusScanService is always called, let's strategify it.
Implement the strategy
The first step is to introduce an interface
public interface VirusScanService { boolean scan(byte[] toScan); }
Then we'll provide two implementations, a null implementation that does nothing and our actual implementation
@Service public class NullVirusScanService implements VirusScanService { @Overide boolean scan(byte[] toScan) { // do nothing return false; } }
@Service public class UvscanVirusScanService implements VirusScanService { @Overide boolean scan(byte[] toScan) { // call the command line 'uvscan' command return false; } }
Now, if nothing else changes, spring will not be able to chose which implementation of our VirusScanService to inject in DocumentService.
Sprinkle some spring powder
We'll configure the application to inject NullVirusScanService by default and turn on the UvscanVirusScanService with the application property feature.virus-scan: uvscan.
@Service @ConditionalOnProperty(name = "feature.virus-scan", havingValue = "null", matchIfMissing = true) public class NullVirusScanService implements VirusScanService { }
@Service @ConditionalOnProperty(name = "feature.virus-scan", havingValue = "uvscan") public class UvscanVirusScanService implements VirusScanService { }
Notice the matchIfMissing in NullVirusScanService that tells spring to use this implementation if no property feature.virus-scan is found.
You can now configure which implementation you want with a simple configuration, this can also be useful to provide fake implementations for your tests.
Happy coding !!
0 notes
Text
Inversion of control and Dependency Injection with Spring
Overview In this article, we will explain concept of Inversion of control (IOC) and Dependency injection (DI) and ways to implement them in spring with simple, clear explanation.
2.Inversion of control (IOC) and Dependency injection (DI) 2.1 Inversion of control with Spring Inversion of control (IOC) is widely used programing principle in which some part/portion of program is controlled by container (in case of spring framework, The IOC container).
Modularity:
Separation of functionality of program into distinct and independent units such that each unit has everything necessary to execute only one aspect of the desired functionality.
Principle use of IOC:
We can use IOC to increase modularity of program and in software terms, more modularity means more extensibility.
In sample way, assume you bought a car and initially you are driving car to company. after few months you reached to higher position. Now you have a lot of work to do so, you appointed a driver to drive you to office so that you can continue your work while you are on the way.
IOC Simplified:
Driving a car your self is same as program without inversion of control Driver is same as Container or Framework Instead of driving car yourself, you appointed driver. You gave control to driver. This is inversion of control. We can ask container to inject dependencies by passing metadata to Spring IOC container.
spring-inversion-of-control Spring Inversion of Control
2.1.1 Pros of Inversion of control (IOC) To decouple task execution from its implementation. To avoid side effects when replacing a module. Objects can be added and tested independently of other objects, because they don’t depend on anything other than what you pass them. 2.1.2 Ways to implement Inversion of Control(IOC) in Spring Inversion of control (IOC) can be implemented by,
factory pattern, service locator pattern dependency injection. 2.2 Dependency Injection in Spring Dependency Injection is used to inject object dependencies when it requires. In simple way, instead of instantiating class dependency in same class, we will inject it at runtime. Through dependency injection, we can achieve loose coupling of objects. If class A uses some functionalities of class B, then we can say, A is dependent on B. In order to call class B’s methods in class A, we have to create class B’s object in class A.
So, instead of creating class B object in class A at compile time, we can inject it on runtime through Dependency Injection.
Let’s make it clear by example,
Seller wants to notify customers about offers through SMS. Have look at following implementation without dependency injection.
Dependency Injection package com.javadevloperzone.spring;
public class Seller {
private SMSService sMSService;
public Seller(){ this.sMSService=new SMSService(); }
public void notifyCustomer(String message,String phoneNumber){ sMSService.sendMessage(message,phoneNumber); }
} package com.javadevloperzone.spring;
public class SMSService {
public void sendMessage(String message,String phoneNumber){ //logic to send sms }
} Description: 1. Seller class is tightly coupled to SMS Service class 2. Seller class has notifyCustomer() method
Now days WhatsApp became one of popular communication medium. Seller decided to inform customers through what’s up.
In this case we should modify Seller class like as follows,
package com.javadevloperzone.spring;
public class Seller {
private WhatsUpService whatsUpService
public Seller(){ this.whatsUpService =new WhatsUpService (); }
public void notifyCustomer(String message,String phoneNumber){ whatsUpService .sendMessage(message,phoneNumber); } } package com.javadevloperzone.spring;
public class WhatsUpService {
public void sendMessage(String message,String phoneNumber){ //logic to send What's Up message } } Every time when seller wants to interact with customers through another medium, we have to change lot of code and testing also become difficult. It might be easier for few dependencies but in real world, there will be more objects have dependency on other objects
Have a look at following code implemented with Dependency injection and abstraction
package com.javadevloperzone.spring;
public class Seller {
private IMessageService messageService;
public Seller(IMessageService messageService){ this.messageService=messageService; }
public void notifyCustomer(String message,String phoneNumber){ messageService.sendMessage(message,phoneNumber); } } package com.javadevloperzone.spring;
public interface IMessageService { public void sendMessage(String message,String phoneNumber); } package com.javadevloperzone.spring;
public class WhatsUpService implements IMessageService {
@Override public void sendMessage(String message,String phoneNumber){ //logic to send What's Up message } } Now Seller class is loosely coupled to its dependency. So in this case the implementation is hidden from task execution. In future, if Seller wants to change, he just needs to change IMessageService class implementation
2.2.1 Ways to implement dependency injection in spring We can implement Dependency Injection with Spring framework in following ways,
Setter Dependency Injection (SDI): by setter method we will inject dependencies Constructor Dependency Injection (CDI): by constructer arguments we will inject dependencies By auto wiring: if we use annotation @Autowired, spring will inject dependencies Mostly used way of injecting dependencies in spring is by auto wiring objects like follows,
package com.javadevloperzone.spring;
@Component public class Seller {
@Autowired private IMessageService messageService;
public void notifyCustomer(String message,String phoneNumber){ messageService.sendMessage(message,phoneNumber); } }
0 notes