#how to create singleton class in java
Explore tagged Tumblr posts
Text
In Java, a Singleton class gives you the power to control object creation, allowing you to simultaneously create a single class object. This article will empower you with the knowledge of singleton classes in Java.
0 notes
Text
i have been vaguely considering making a minecraft mod, but every time i think about the specifics of it i remember how intensely java-brained forge was back in the days and i'm like "how likely is it that any of the 4 competing modloaders have actually made themselves less java brained in the past uhhh seven years" and i don't really want to dig in
also b/c i'm using an outdated version of ubuntu i'd have to do a complete system reinstall to get access to apt back and be able to set up a java development environment
(when i say 'java brained' the specific thing i'm thinking of was to register blocks you had to provide a class for it to autoinstance. you could not provide, you know, an object that was an instance of the block-provididing class, you had to make a singleton class. just the classic java thing of instead of having classes with parameters which you create specific instances of, you have classes that have derived classes that are only ever expected to be instanced with a blank constructor b/c all the specific object data is in the class definition instead of being able to be specified on the object level. the classic 'we don't have first-class functions so it's impossible to vary a function callback' java thing, & it was enshrined into forgemodloader at the most basic level.)
8 notes
·
View notes
Text
Most useable core Creational Design Patterns in Java(Singleton & Prototype)
Explore how Singleton and Prototype patterns streamline Java applications by enhancing performance, reuse, and maintainability in real-world scenarios.
Design patterns are tried-and-tested solutions to common software design problems. In Java, they help developers write clean, reusable, and scalable code. This post focuses on two creational design patterns: 1. Singleton Design Pattern 2. Prototype Design Pattern
1. Singleton Design Pattern: The Singleton pattern ensures a class has only one instance and provides a global point of access to it.
Why Use It: Use Singleton when you want exactly one object to coordinate actions across the system. It’s perfect for things like: Configuration settings Database connections Thread pools Logging Caches
Java Implementation (Thread-Safe Singleton): public class ConfigManager { private static volatile ConfigManager instance;
private ConfigManager() { // private constructor }
public static ConfigManager getInstance() { if (instance == null) { synchronized (ConfigManager.class) { if (instance == null) { instance = new ConfigManager(); } } } return instance; }
public void printConfig() { System.out.println(“App config data…”); } }
Database Connection Manager: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
public class DatabaseConnectionManager { private static volatile DatabaseConnectionManager instance; private Connection connection; private static final String URL = “jdbc:mysql://localhost:3306/app_db”; private static final String USER = “root”; private static final String PASSWORD = “password”;
private DatabaseConnectionManager() { try { this.connection = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { throw new RuntimeException(“Failed to connect to DB”, e); } }
public static DatabaseConnectionManager getInstance() { if (instance == null) { synchronized (DatabaseConnectionManager.class) { if (instance == null) { instance = new DatabaseConnectionManager(); } } } return instance; }
public Connection getConnection() { return connection; } }
public class UserService { public void getUserData() { try { Connection conn = DatabaseConnectionManager.getInstance().getConnection(); // Use the connection for a query (using Statement, PreparedStatement, etc.) } catch (Exception e) { e.printStackTrace(); } } }
2. Prototype Design Pattern: The Prototype pattern lets you clone existing objects instead of creating new ones from scratch. It’s especially useful when object creation is expensive (e.g., loading from DB, complex setup).
Why Use It: When object construction is costly. When you need many similar objects with slight variations. When you want to avoid subclassing Document Template System: Building an enterprise app that generates business reports (invoices, summaries, charts). Each report starts from a base template, but the content is customized per user or client.
Instead of recreating everything from scratch, we clone a base report object and make changes.
public class ReportTemplate implements Cloneable { private String title; private String content; private String footer;
public ReportTemplate(String title, String content, String footer) { this.title = title; this.content = content; this.footer = footer; }
public void setContent(String content) { this.content = content; }
public void print() { System.out.println(“=== “ + title + “ ===”); System.out.println(content); System.out.println(“ — — “ + footer + “ — -”); }
@Override public ReportTemplate clone() { try { return (ReportTemplate) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(“Failed to clone ReportTemplate”, e); } } }
public class Main { public static void main(String[] args) { // Base template ReportTemplate monthlyReport = new ReportTemplate( “Monthly Report”, “This is a placeholder content.”, “Confidential” );
// Clone for Client A ReportTemplate clientAReport = monthlyReport.clone(); clientAReport.setContent(“Revenue: $10,000\nProfit: $2,500”);
// Clone for Client B ReportTemplate clientBReport = monthlyReport.clone(); clientBReport.setContent(“Revenue: $12,000\nProfit: $3,000”);
// Display both clientAReport.print(); clientBReport.print(); } }
When to Use What: Use Case Singleton Prototype One shared instance needed ✅ ❌ Performance matters in object creation ❌ ✅ Slight variations of the same object ❌ ✅ Global access point required ✅ ❌
Test yourself on what you’ve learned above, and compare your answers with the correct ones provided below.
Q1. What is the main purpose of the Singleton pattern? A. Ensure multiple instances of a class B. Allow cloning of objects C. Ensure only one instance of a class D. Avoid subclassing
Please visit our website to know more:-https://cyberinfomines.com/blog-details/most-useable-core-creational-design-patterns-in-java%28singleton-&-prototype%29
0 notes
Text
Learning Design Patterns in Programming
Design patterns are reusable solutions to common software design problems. Whether you're a beginner or an experienced developer, learning design patterns can greatly improve your ability to write clean, scalable, and maintainable code. This post introduces the concept of design patterns, why they're important, and how you can start using them effectively in your projects.
What Are Design Patterns?
A design pattern is a proven way to solve a specific problem in software design. These patterns are not code snippets but templates or best practices that guide developers in structuring their programs.
Why Use Design Patterns?
Code Reusability: Promotes the use of reusable solutions.
Scalability: Makes it easier to scale applications.
Maintainability: Leads to cleaner and more organized code.
Team Collaboration: Helps teams follow a shared vocabulary and approach.
Problem Solving: Speeds up decision-making by providing tried-and-tested approaches.
Categories of Design Patterns
Creational Patterns: Focus on object creation mechanisms (e.g., Singleton, Factory).
Structural Patterns: Deal with object composition (e.g., Adapter, Decorator).
Behavioral Patterns: Manage communication and behavior (e.g., Observer, Strategy).
Common Design Patterns Explained
1. Singleton Pattern
Ensures a class has only one instance and provides a global access point to it.// Singleton in Java public class Database { private static Database instance; private Database() {} public static Database getInstance() { if (instance == null) { instance = new Database(); } return instance; } }
2. Factory Pattern
Creates objects without exposing the instantiation logic to the client.// Factory Example in Python class ShapeFactory: def get_shape(self, type): if type == 'circle': return Circle() elif type == 'square': return Square()
3. Observer Pattern
Defines a one-to-many dependency so that when one object changes state, all its dependents are notified.
4. Strategy Pattern
Allows algorithms to be selected at runtime by defining a family of interchangeable behaviors.
5. Decorator Pattern
Adds new functionality to objects dynamically without changing their structure.
Best Practices for Learning Design Patterns
Start with the basics: Singleton, Factory, and Observer.
Understand the problem each pattern solves.
Use real-world examples to grasp each pattern.
Refactor your existing code using design patterns where applicable.
Don't force patterns—use them where they naturally fit.
Resources for Learning
Refactoring Guru – Visual and code-based examples.
SourceMaking – Classic explanations.
Java Design Patterns GitHub Repo
Book: Design Patterns: Elements of Reusable Object-Oriented Software by the "Gang of Four".
Conclusion
Design patterns are a powerful tool for developers at all levels. They provide a structured approach to solving common programming problems and help build applications that are easier to manage and extend. Start small, practice often, and soon you'll be writing better code with confidence.
0 notes
Text
Mastering Java Design Patterns: Singleton, Factory, and Observer
Design patterns are essential for writing scalable, reusable, and maintainable Java applications. In this blog, we’ll dive into three widely used creational and behavioral design patterns: Singleton, Factory, and Observer.
1. Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global access point to it. This is useful in scenarios like database connections, logging, or thread pools.
Implementation of Singleton Pattern
Here’s how you can implement a thread-safe Singleton in Java using the lazy initialization approach with double-checked locking:javapublic class Singleton { private static volatile Singleton instance; private Singleton() { // Private constructor prevents instantiation } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
When to Use Singleton Pattern
Database connections (e.g., connection pools).
Logging (ensuring only one logger instance).
Caching (storing frequently accessed data).
2. Factory Pattern
The Factory pattern is a creational design pattern that provides an interface for creating objects without specifying their concrete class. It promotes loose coupling and code reusability.
Implementation of Factory Pattern
Let’s create a Factory for different shapes:java// Step 1: Define an interface interface Shape { void draw(); }// Step 2: Implement different shape classes class Circle implements Shape { public void draw() { System.out.println("Drawing a Circle"); } }class Rectangle implements Shape { public void draw() { System.out.println("Drawing a Rectangle"); } }// Step 3: Create the Factory class class ShapeFactory { public static Shape getShape(String shapeType) { if (shapeType.equalsIgnoreCase("CIRCLE")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("RECTANGLE")) { return new Rectangle(); } return null; } }// Step 4: Using the Factory public class FactoryPatternExample { public static void main(String[] args) { Shape shape1 = ShapeFactory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = ShapeFactory.getShape("RECTANGLE"); shape2.draw(); } }
When to Use Factory Pattern
When object creation logic is complex.
When you need to return different subclasses based on input.
To decouple object creation from the client code.
3. Observer Pattern
The Observer pattern is a behavioral design pattern that establishes a one-to-many dependency between objects. When one object (subject) changes, all its dependent objects (observers) are notified automatically.
Implementation of Observer Pattern
Let’s create a Publisher-Subscriber (Observer) system:javaimport java.util.ArrayList; import java.util.List;// Step 1: Define the Observer interface interface Observer { void update(String message); }// Step 2: Create a Concrete Observer class User implements Observer { private String name; public User(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + " received notification: " + message); } }// Step 3: Create the Subject (Publisher) interface interface Subject { void addObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(String message); }// Step 4: Implement Concrete Subject class NotificationService implements Subject { private List<Observer> observers = new ArrayList<>(); @Override public void addObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } }// Step 5: Using the Observer Pattern public class ObserverPatternExample { public static void main(String[] args) { NotificationService service = new NotificationService(); Observer user1 = new User("Alice"); Observer user2 = new User("Bob"); service.addObserver(user1); service.addObserver(user2); service.notifyObservers("New Video Uploaded!"); } }
When to Use Observer Pattern
Implementing event-driven systems.
In real-time updates (e.g., stock price updates, chat applications).
Decoupling subjects from observers to promote flexibility.
Conclusion
These three patterns are fundamental in Java application development:
✅ Singleton: Ensures only one instance exists (e.g., database connections). ✅ Factory: Creates objects dynamically (e.g., UI components, shape creators). ✅ Observer: Implements event-driven communication (e.g., notification services).
By mastering these patterns, you can write cleaner, maintainable, and scalable Java code. 🚀
0 notes
Text
Key Concepts to Review Before Your Java Interview
youtube
Java interviews can be both challenging and rewarding, often acting as a gateway to exciting roles in software development. Whether you're applying for an entry-level position or an advanced role, being well-prepared with core concepts is essential. In this guide, we’ll cover key topics to review before your Java interview, ensuring you're confident and ready to impress. Additionally, don't forget to check out this detailed video guide to strengthen your preparation with visual explanations and code demonstrations.
1. Object-Oriented Programming (OOP) Concepts
Java is known for its robust implementation of OOP principles. Before your interview, make sure to have a firm grasp on:
Classes and Objects: Understand how to create and use objects.
Inheritance: Review how subclasses inherit from superclasses, and when to use inheritance.
Polymorphism: Know the difference between compile-time (method overloading) and runtime polymorphism (method overriding).
Abstraction and Encapsulation: Be prepared to explain how and why they are used in Java.
Interview Tip: Be ready to provide examples of how you’ve used these concepts in your projects or coding exercises.
2. Core Java Concepts
In addition to OOP, there are foundational Java topics you need to master:
Data Types and Variables: Understand primitive types (int, double, char, etc.) and how they differ from non-primitive types.
Control Structures: Revise loops (for, while, do-while), conditional statements (if-else, switch-case), and how they control program flow.
Exception Handling: Know how try, catch, finally, and custom exceptions are used to manage errors in Java.
Collections Framework: Familiarize yourself with classes such as ArrayList, HashSet, HashMap, and their interfaces (List, Set, Map).
Interview Tip: Be prepared to discuss the time and space complexities of different collection types.
3. Java Memory Management
Understanding how Java manages memory can set you apart from other candidates:
Heap vs. Stack Memory: Explain the difference and how Java allocates memory.
Garbage Collection: Understand how it works and how to manage memory leaks.
Memory Leaks: Be prepared to discuss common scenarios where memory leaks may occur and how to avoid them.
Interview Tip: You may be asked how to optimize code for better memory management or to explain how Java’s finalize() method works.
4. Multithreading and Concurrency
With modern applications requiring multi-threading for efficient performance, expect questions on:
Threads and the Runnable Interface: Know how to create and run threads.
Thread Lifecycle: Be aware of thread states and what happens during transitions (e.g., from NEW to RUNNABLE).
Synchronization and Deadlocks: Understand how to use synchronized methods and blocks to manage concurrent access, and how deadlocks occur.
Concurrency Utilities: Review tools like ExecutorService, CountDownLatch, and Semaphore.
Interview Tip: Practice writing simple programs demonstrating thread synchronization and handling race conditions.
5. Java 8 Features and Beyond
Many companies expect candidates to be familiar with Java’s evolution, especially from Java 8 onward:
Lambda Expressions: Know how to write concise code with functional programming.
Streams API: Understand how to use streams for data manipulation and processing.
Optional Class: Learn to use Optional for handling null checks effectively.
Date and Time API: Review java.time package for managing date and time operations.
Interview Tip: Be prepared to solve coding problems using Java 8 features to show you’re up-to-date with recent enhancements.
6. Design Patterns
Java interviews often include questions on how to write clean, efficient, and scalable code:
Singleton Pattern: Know how to implement and when to use it.
Factory Pattern: Understand the basics of creating objects without specifying their exact class.
Observer Pattern: Be familiar with the publish-subscribe mechanism.
Decorator and Strategy Patterns: Understand their practical uses.
Interview Tip: Have examples ready that demonstrate how you’ve used these patterns in your projects.
7. Commonly Asked Coding Problems
Prepare by solving coding problems related to:
String Manipulations: Reverse a string, find duplicates, and check for anagrams.
Array Operations: Find the largest/smallest element, rotate arrays, or merge two sorted arrays.
Linked List Questions: Implement basic operations such as reversal, detecting cycles, and finding the middle element.
Sorting and Searching Algorithms: Review quicksort, mergesort, and binary search implementations.
Interview Tip: Practice on platforms like LeetCode or HackerRank to improve your problem-solving skills under time constraints.
Final Preparation Tips
Mock Interviews: Conduct practice interviews with peers or mentors.
Review Your Code: Ensure your past projects and code snippets are polished and ready to discuss.
Brush Up on Basics: Don’t forget to revise simple concepts, as interviews can include questions on any level of difficulty.
For more in-depth preparation, watch this helpful video that provides practical examples and coding tips to boost your confidence.
With these concepts in mind, you'll be well-equipped to handle any Java interview with poise. Good luck!
0 notes
Text
30 Java Full Stack Developer interview questions for Freshers

Are you an aspiring programmer seeking to start a professional journey as a Java Full Stack Developer? As you venture into the realm of web and software development, it is essential to equip yourself with the necessary skills and knowledge to effectively tackle the forthcoming challenges. Getting your first job as a Full Stack Developer is a big achievement, and to assist you, we have created a list of 30 Java Full Stack Developer interview questions specifically designed for beginners.
1. What is Java Full Stack Development?
Java Full Stack Development refers to the development of web applications using both front-end and back-end technologies, with Java as the primary programming language.
2. Explain the difference between front-end and back-end development.
Front-end development focuses on the user interface and client-side functionality, while back-end development deals with server-side logic and database interactions.
3. What are the key components of a typical web application stack?
A typical web application stack consists of a front-end framework (e.g., React, Angular), a back-end server (e.g., Spring Boot), and a database (e.g., MySQL).
4. What is Java Virtual Machine (JVM) and why is it important in Java development?
JVM is an essential part of Java that interprets Java bytecode and allows cross-platform compatibility. It plays a crucial role in running Java applications.
5. What is a servlet, and how does it relate to Java web development?
A servlet is a Java class used to extend the capabilities of servers and provide dynamic content. It is commonly used in Java web development to handle HTTP requests and responses.
6. Explain the Model-View-Controller (MVC) architectural pattern.
MVC is an architectural pattern that separates an application into three interconnected components: Model (data), View (user interface), and Controller (handles user input and updates the model and view).
7. What is Spring Framework, and how does it simplify Java development?
Spring is a popular Java framework that simplifies Java development by providing features like dependency injection, AOP, and MVC for building scalable and maintainable applications.
8. Describe RESTful web services and their importance in Java development.
RESTful web services are a way to build lightweight and scalable APIs using HTTP methods. They are essential for building modern web applications in Java.
9. What is Hibernate, and how does it relate to database interaction in Java?
Hibernate is an ORM (Object-Relational Mapping) framework that simplifies database interaction in Java by mapping Java objects to database tables.
10. Explain the concept of dependency injection in Spring.
Dependency injection is a design pattern used in Spring to manage component dependencies. It allows for loosely coupled and easily testable code by injecting dependencies rather than creating them.
11. What is a singleton pattern, and why is it relevant in Java development?
The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It’s used to manage resources like database connections efficiently.
12. What is the difference between GET and POST HTTP methods?
GET is used for retrieving data from the server, while POST is used for sending data to the server for processing or storage.
13. What is SQL injection, and how can it be prevented in Java applications?
SQL injection is a security vulnerability where malicious SQL code is injected into user inputs. To prevent it, use parameterized queries and input validation.
14. Explain the purpose of a web container in Java EE applications.
A web container is responsible for managing the lifecycle of servlets and JSP pages in Java EE applications. (e.g., Tomcat)
15. What is a session in web applications, and how is it managed in Java?
A session is a mechanism to maintain user-specific data across multiple HTTP requests. In Java, sessions can be managed using cookies or URL rewriting.
16. What is the difference between forward and sendRedirect in servlets?
forward is used to forward the request and response objects to another resource within the same server, while sendRedirect sends a response with a new URL, causing a new request.
17. Explain the purpose of the @RequestMapping annotation in Spring MVC.
@RequestMapping is used to map a URL request to a specific controller method in Spring MVC, allowing for proper routing of requests.
18. What is a RESTful API endpoint, and how is it structured?
A RESTful API endpoint is a URL pattern that represents a resource and its actions. It typically follows a structured format, such as /resource/{id}.
19. What is CORS, and why is it important in web development?
CORS (Cross-Origin Resource Sharing) is a security feature that allows or restricts web pages in one domain from making requests to a different domain. It’s essential for security in web development.
20. What is the purpose of the web.xml file in Java web applications?
The web.xml file is a configuration file in Java web applications that defines servlets, filters, and their mappings, among other things.
21. Explain the concept of microservices and their advantages.
Microservices is an architectural style where an application is composed of small, independently deployable services. Advantages include scalability, maintainability, and flexibility.
22. What is Docker, and how does it facilitate deployment in Java development?
Docker is a containerization platform that allows developers to package applications and their dependencies into containers for consistent and efficient deployment.
23. What is the purpose of a version control system like Git in software development?
Git is used for tracking changes in code, collaborating with others, and maintaining a history of code revisions, which is essential for code management and collaboration.
24. How does Maven help in managing project dependencies in Java?
Maven is a build automation tool that simplifies the process of managing project dependencies, building projects, and producing artifacts.
25. What is the purpose of JUnit in Java development, and how is it used for testing?
JUnit is a testing framework used for writing and executing unit tests in Java. It ensures that individual components of the code function correctly.
26. Explain the concept of continuous integration (CI) and continuous delivery (CD).
CI involves regularly merging code changes into a shared repository, while CD automates the process of deploying code changes to production, ensuring a streamlined development workflow.
27. What is the Spring Boot framework, and how does it simplify Java application development?
Spring Boot is a framework that simplifies the setup and configuration of Spring applications, allowing developers to quickly build production-ready applications with minimal effort.
28. What are the key principles of the SOLID design principles in Java development?
SOLID is an acronym representing five design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. These principles promote clean and maintainable code.
29. What is the purpose of the @Autowired annotation in Spring?
@Autowired is used for automatic dependency injection in Spring, allowing Spring to automatically resolve and inject dependencies into a class.
30. How can you secure a Java web application against common security threats?
Secure a Java web application by implementing proper authentication, authorization, input validation, using encryption, and regularly updating dependencies to patch vulnerabilities.
#datavalley#dataexperts#data engineering#data analytics#dataexcellence#business intelligence#data science#power bi#data analytics course#data science course#java#java full stack developer#java interview questions#java full stack course#java full stack training#full stack devlopement
0 notes
Text
8 Tips to Up Your Java Game
Certainly! Here are eight tips to help you improve your Java programming skills:
Practice Object-Oriented Programming (OOP): Java is an object-oriented programming language, so it's important to understand the principles and concepts of OOP. Familiarize yourself with classes, objects, inheritance, polymorphism, and encapsulation.
Master the Java APIs: Java provides a vast array of APIs (Application Programming Interfaces) that offer pre-built functionality. Get familiar with the commonly used APIs like the Collections Framework, I/O classes, and the Java Concurrency API. Understanding these APIs will make your code more efficient and maintainable.
Use Generics: Generics allow you to create reusable code by providing type safety and avoiding unnecessary type casting. Utilize generics when working with collections, custom data structures, and algorithms to improve code readability and maintainability.
Learn and Apply Design Patterns: Design patterns are reusable solutions to common programming problems. Understanding and applying design patterns will help you write more modular, flexible, and maintainable code. Some popular design patterns in Java include Singleton, Factory, Observer, and Strategy patterns.
Practice Exception Handling: Java's exception handling mechanism helps you handle errors and exceptions gracefully. Learn about checked and unchecked exceptions and understand when to use try-catch blocks. Proper exception handling improves the reliability and robustness of your code.
Utilize Multithreading: Java has excellent support for multithreading, allowing you to create concurrent and parallel applications. Explore the Java Concurrency API and learn how to use threads, synchronization, locks, and thread pools effectively. This knowledge will enable you to write scalable and efficient programs.
Use IDEs and Debugging Tools: Employing Integrated Development Environments (IDEs) like IntelliJ IDEA, Eclipse, or NetBeans can significantly boost your productivity. These IDEs provide features like code completion, debugging, and refactoring tools that streamline your development process.
Read and Contribute to Open-Source Projects: Engaging with open-source projects can expose you to best practices, coding standards, and collaborative development. Browse popular Java open-source projects on platforms like GitHub, study their codebase, and contribute by fixing bugs or adding new features. This hands-on experience will enhance your skills and expand your knowledge.
Remember, consistent practice and continuous learning are essential for improving your Java programming abilities. Keep challenging yourself with new projects, coding exercises, and exploring advanced Java topics.
1 note
·
View note
Text
TOP 10 ADVANCED JAVA INTERVIEW QUESTIONS
In the tech universe, knowing almost all the necessary scripts is an advantage. One of the essential languages to get hold of is Java, a programming language and computing platform released in 1995 by Sun Microsystems.
Twenty-five years of its existence has only strengthened its prominence in the programming arena. Today, it is used by nearly more than ten million developers across the globe. Hence, learning Java is worth every minute. Srishti Campus is the best Java Training Centre in Trivandrum, Kerala.
Here are top-ten advanced java interview questions that can help you land the job of your choice.
What all platforms does Java support?
It is a fundamental question that can be asked at every interview panel. Java is a language that runs on many platforms. The popular platforms that support Java include Windows, Mac OS, Linux UNIX, etc.
What exactly is Reflection? Explain with its uses.
Java reflections are the runtime API used to inspect and change the behaviour of interfaces, methods, and classes. They help the user to make new objects, get field values, and call methods. It also analyzes classes, fields, interfaces, and methods in runtime. Reflection can also be used by debuggers to examine private members of classes. To learn more about such questions, Srishti Campus is the best online java training centre.
Why is Java an independent platform?
Java is an independent platform because of its ability to run anywhere. In other words, the bytecodes can run on any system despite its underlying operations. Java Training Institution can help aspiring candidates learn more about the program.
What are Daemon Threads in Java?
They are typically like service providers for other threads or objects running as daemon threads. Their importance arises when normal threads are executed, and the threads are otherwise used for background supporting tasks.
What is singleton?
It is a class which permits only a single instance of itself to be created by giving access for its creation. It is primarily used when a user limits instantiation of classes to one subject. It also contains private and unique instances. It can be of immense help when a single object needs to coordinate actions across the system.
What is Java Servlet?
The Java Servlet is a server-side technology designed to facilitate the extension of web servers by providing dynamic response and data persistence.
Why is Java not Object Oriented?
Java is the language that uses eight primitive data types ranging from char, int, char, boolean, float, short, double, long, and byte, and these are not objects.
What does Java Bean mean?
Beans comprise the cardinal scope of the spring framework. It is managed by the Spring IOC container.
How is equals () different from = = in Java?
The Object class in Java defines the Equals() method for comparing two objects defined by business logic. “Equal” or “= =” is a binary operator provided by Java and used to compare primitives and objects. The implementation at the default stage uses the = = operator for the comparison of two objects.
What does multiple inheritance mean? As the name goes, it is a process by which multiple parent class properties are inherited by a child class. It is also known as the diamond problem and is, however, supported by Java.
Srishti Campus provides the best Java training in Trivandrum. Our world-class Java Training will help you to become a Java expert. We offer them the most credible placement assistance and certification guidance for java training in Trivandrum. inter is one of the reputed institutions providing the most competitive learning in Java and other technical courses. We offer the best curriculum prepared through proper research by experts. Become a certified Java Developer with our unique course!!
0 notes
Text
Oxford Certified Advance Java Professional

Oxford Certified Advance Java Professional
A Step ahead of Core Java – Advanced Java focuses on the APIs defined in Java Enterprise Edition, includes Servlet programming, Web Services, the Persistence API, etc. Oxford Software Institute provides the best classes in Advanced Java in Delhi and our course includes advanced topics like creating web applications by using technologies like Servlet, JSP, JSF, JDBC, EJB etc. We will further learn enterprise applications used a lot in banking sector.
JDBC, SERVLET AND JSP
The course will focus on JDBC, JDBC Drivers, Setting up a database and creating a schema, Connecting to DB, CRUD Operations, Rowset, Resultset, Preparedstatement, Connection Modes and much more. We will further learn the Basics of Servlet, Servlet Life Cycle, Working with Apache Tomcat Server, Servlet with JDBC, Servlet Collaboration, servletconfig, servletcontext, Attribute, Session, Tracking, Event and Listener, Filter, ServletInputStream etc. Under JSP, we’ll learn Basics of JSP, API, JSP in netbeans, Implicit Objects, Directive Elements, Taglib, Exception Handling, Action Elements, Expression Language, MVC, JSTL etc.
JAVAMAIL API, JMS AND JAVA NETWORKING
Under these topics, Oxford Software Institute offers best classes in Advanced Java such as Sending Email, Sending Email through Gmail server, Receiving Email, Sending HTML content, JMS Overview, JMS Messaging Domains, Example of JMS using Queue, Example of JMS using Topic, Networking Concepts, Socket Programming, URL class, URLConnection class, HttpURLConnection, InetAddress class, DatagramSocket class.
JQUERY, AJAX, MAVEN AND DAO PATTERN
The content has been prepared with utmost care at Oxford Software Institute where we provide the best classes with topics such as Introduction to JQuery, Validation, Forms, , Introduction to AJAX, Servlet and JSP with AJAX, Interacting with database, Maven, Ant Vs Maven, How to install Maven, Maven Repository, Understanding pom.xml, Maven Example, Maven Web App Example, Maven using NetBeans, DAO pattern, Singleton, DAO, DTO, MVC, Front Controller, Factory Method.
HIBERNATE AND SPRING FRAMEWORK
This session will focus on HB Introduction and Architecture, Hibernate with NetBeans, HB using XML, HB using Annotation, Web application, Generator classes, Dialects, Log4j, Inheritance Mapping, Mapping, Transaction Management, HQL, HCQL, Named Query, Caching, Second Level Cache, Integration, Struts. We will further learn about Spring Modules, Spring in NetBeans , Dependency Injection, JdbcTemplate, ORM, SPEL, MVC, MVC Form Tag Library, MVC Validation, MVC Tiles, Spring Remoting, OXM, Java Mail, Spring Security , Spring + Angular, CRUD Example, File Upload Example, Login & Logout Example, Search Field Example.
REST - REPRESENTATIONAL STATE TRANSFER
This session will focus on Installation of Jersey, Web container, required setup for Gradle and Eclipse web projects, How to Create your first RESTful WebService, How to Create a REST client, RESTful web services and JAXB, CRUD RESTful WebService, Rest Resources. We, at Oxford Software Institute will provide best classes that will focus on the practical applications of these concepts
SOFT SKILLS
Having a technical and discipline-specific expertise can help you get to the interview room but it’s the soft skills that will make the hiring manager hand you the appointment letter. In this course, students will also learn various Soft Skills like how to communicate professionally in English, Speaking in public without hesitation, using effective gestures and postures to appear impressive, managing stress and emotions and taking successful interviews. Oxford Software Institute provides the best classes in Soft-skill training.
CERTIFICATIONS*
During this course, students will be trained for the following certifications
Oxford Certified Advance Java Professional.
0 notes
Text
Spring Boot VS Spring Framework: Razor-Sharp Web Applications
Looking back at last few years, the Spring framework has become quite complex due to added functionalities. As a result, it takes enormous time and lengthy processes to start a new Spring project. However, to cut down the extra time and effort, Spring Boot was introduced. Using Spring framework as a foundation, Spring Boot is becoming the most preferred framework lately. The question: Spring Boot vs Spring, which is better, still hovers on the mind of many developers.
That said, you might be intrigued by questions like what Spring Boot is and their goals? How is Spring Framework vs Spring Boot different, and how can we compare them? This guide states the basics and Spring Boot vs Spring Framework difference, along with their features and advantages. The guide also states how spring Boot has solved the problems faced with spring. By the end of this guide, you will get precise knowledge about choosing Spring Boot over the spring framework. Straightaway, let’s get started with the Spring VS Spring Boot discussion in detail!
Spring Framework
Spring is a lightweight open-source framework that enables Java EE7 developers to develop reliable, scalable, and simple enterprise applications. It is one of the widely used Java Frameworks to build applications. When it comes to the Java platform, Spring offers an exclusive programming and configuration model.
This framework aims to offer multiple ways to assist you in handling your business objects by simplifying the Java EE development and helping developers be more productive. Spring considers the current business needs and works on fulfilling them.
With Spring, the development of web applications has become quite easy as compared to the classic Application Programming Interfaces(APIs) and Java frameworks like JavaServer Pages(JSP), Java Database Connectivity(JDBC), and Java Servlets. Spring framework adopts new techniques like Plain Old Java Object(POJO), Aspect-Oriented Programming(AOP), and Dependency Injection(DI) to build enterprise applications.
In other terms, the Spring Framework can also be referred to as a set of sub-frameworks or layers like Spring AOP, Spring Web Flow, Spring ORM(object-relational mapping), and Spring Web MVC. These modules collectively can offer better functionalities for a web application.
Benefits Of Spring Framework
Quite a lightweight framework considering the POJO model
Supports Declarative programming
Supports both annotation and XML configurations
Offers middleware services
Enables easy testability and loose coupling
Eliminates the formation of factory classes and singleton.
Best Features Of Spring Framework
The Spring Framework has several features that are disintegrated into 20 modules to solve several problems. A few more popular Spring Modules include,
Spring JDBC
Spring MVC
Spring ORM
Spring Test
Spring AOP
Spring JMS
Spring Expression Language(SpEL)
Dissimilar to other frameworks, Spring works on specific areas of any application. One chief feature of Spring is the dependency injection. The dependency injection helps to make things simpler by enabling developers to build loosely coupled applications.
Having said that, despite having multiple benefits to offer, why should you choose Spring Boot? To be more precise, what led to the introduction of Spring Boot?
How Spring Boot Emerged?
With the help of Spring Boot, you can simplify and use the Spring framework easily. While Spring offers loosely coupled applications, it becomes a tedious and difficult task to keep track of the loosely coupled blocks. This is exactly where Spring Boot comes to play.
With the Spring architecture becoming complicated day by day, introducing Spring Boot was necessary. To begin a new project in Spring involves varied processes. When you want to build a Spring framework app, multiple similar configurations need to apply manually. Consequently, it needs to specify frameworks that are to be used and select compatible versions as well. Hence, Spring developers introduced a new framework known as the Spring Boot.
Spring Boot
Spring Boot is built over the Spring framework. Hence, it offers all the features of spring. Spring Boot is a microservice-based framework that enables you to build your app in a shorter time. Each element in Spring Boot is auto-configured. Developers simply need to use accurate configuration to use certain functionality. In case you wish to develop REST API, Spring Boot is highly recommended!
Besides offering utmost flexibility, Spring Boot focuses on shortening the code length, providing you with the easiest method to build a Web application. Featuring default codes and annotation configuration, this framework reduces the time taken to develop an application. In other words, Spring Boot helps to build a stand-alone application with almost zero configuration.
Benefits Of Spring Boot
It does not need XML configuration
It builds stand-alone applications
Compared to Spring, Spring Boot is easier to launch
Spring Boot does not ask you to deploy WAR files
It focuses on reducing the LOC
It helps to embed Jetty, Undertow, or Tomcat directly
Offers easy management and customization
Provides production-ready features.
Spring Boot is typically an extension of Spring Framework that removes the boilerplate configurations needed to set up a fast and efficient Spring application.
Best Features Of Spring Boot
A few features of Spring Boot include,
Embedded server to eliminate complexities in application development
Opinionated starter dependencies to ease the build and app configuration
Auto-configuration for Spring functionality: A chief feature that configures the class based on a specific requirement automatically. It saves you from noting lengthy codes and avoid unnecessary configuration
Health check, metrics, and externalized configuration.
Spring Boot Starter Dependencies
Spring Boot offers a range of starter dependencies for distinct spring modules. Some of the common starter dependencies that allow easy integration include,
spring-boot-starter-data-jpa
spring-boot-starter-security
spring-boot-starter-test
spring-boot-starter-web
spring-boot-starter-thymeleaf
What Makes Spring Boot So Popular?
To answer this question, the first point to be noted is that Spring Boot is based on Java. Java being the most popular programming language globally, there is no doubt why Spring Boot is gaining popularity. Besides this, Spring Boot helps you build an application quickly without worrying about the accuracy and safety of the configuration.
Spring Boot has a vast user community. This further denotes that you can easily find learning courses and materials. Spring Boot is further useful while performing repetitive or long operations.
Advantages Of Spring Boot Over Spring: Spring VS Spring Boot
A few additional benefits include,
Assists in autoconfiguration of all components for a production-grade Spring application
Increases the efficiency of the developmental team
Eliminates manual work that includes annotations, complicated XML configurations, and boilerplate code
Creates and tests Java-based apps by offering a default setup for integration and unit tests
Features embedded HTTP serves such as Tomcat and Jetty to test applications
Offers great admin support. You can handle and monitor through remote access to the application.
Enables easy connecting with queue services and databases such as Redis, Oracle, MySQL, ElasticSearch, PostgreSQL, MongoDB, ActiveMQ, Solr, Rabbit MQ, etc
Integration of Spring Boot with spring ecosystem is easy
Provides flexibility in configuring Database Transaction, Java Beans, and XML configurations
Simplifies the dependency
Tags an embedded Servlet Container along with it
Default configurations allow faster application bootstrapping
Spring Boot does not require a deployment descriptor like the Spring framework.
Read More: Why Choose Spring Boot Over Spring Framework?
0 notes
Link
In this article we’ve collected the most commonly asked Java Interview Questions for freshers and job seekers in Java. These questions will familiarize you with the types of questions an interviewer will ask you during your Java Programming interview. As a Fresher, you have either attended or will soon attend an interview. You may be worried about the upcoming interviews as an Entry Level job seeker trying to advance your career in software programming. If you want to start a career in Java web app development, you’ve come to the right place! We’ve put together a rundown of the most often requested Java interview questions to help you pass your Java career interview.
Java Interview Questions
Let us have a look at the major Java interview questions.

Question 1: What is Java?
Java is a general-purpose ,object-oriented and a high-level programming language.
Question 2: What is Java Virtual Machine?
JVM is a program that helps to interpret the intermediate Java byte code and generates the desired output.
Question 3: Explain the feature of Java platform independent?
Java JVM can covert the source code into corresponding byte codes these byte codes can be run on any OS independent of the platform.
Question 4: What is mean by singleton class in Java ?
The singleton class is the that can be create only one instance at any time in one JVM.
Question 5: What are access modifiers in Java?
Access modifiers in Java specifies the scope and visibility of Java variable.
The four Java access modifiers are
1. Default
2. Private
3. Protected
4. Public
Question 6: Why Java Strings are immutable in nature?
Java Strings are immutable which meaning that the value of Java string variable can’t be modified or unchanged. We can change the values only by specifying it by using a StringBuffer or StringBuilder.
Question 7: What is Request Dispatcher?
The Request Dispatcher is used to sending the request to another resource of the type html, servlet or jsp.
The methods of Request Dispatcher are
1.void forward()
2.void include()
Question 8: What is the life-cycle of a servlet?
1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. Servlet is destroyed
Question 9: Explain different methods of session management in servlets?
Common session management methods are
1. User Authentication
2. HTML Hidden Field
3. Cookies
4. URL Rewriting
5. Session Management API
Question 10: How to integrate Spring and Hibernate Frameworks?
Hibernate and Spring are Java frameworks they are integrated with help of DAOpattern and its dependency injection.
Question 11: Is it possible to restrict Inheritance in Java?
Yes, inheritance in Java can be restricted by using the following methods
1. By using the final keyword. 2. By making the methods as final. 3. By using private constructor in a class. 4. By using (//) Javadoc comment in a Java program
Question 13: What is the function of a constructor in a Java class?
Java class constructors are used to initialize the state of any object only after creating an object using the new keyword.
Question 14:What is the use of looping?
Loops in Java help the programmer to execute a part of program repeatedly in several times. Java have for , while and do-while as looping statements.
Question 15:How to perform Java Database Connectivity in a Java program?
The five major steps to achieve JDBC(Java Database Connectivity) are
1. Register the driver class
2. Create the connection
3. Create the statement
4. Execute the queries
5. Close the connection
Question 16:What Is the concept of Multi-Threading in Java?
Multi-threading is the process of executing multiple task simultaneously. In Java Multi-threading is achieved by using extending from Thread class or implementing from Runnable interface.
Question 17: What are Packages in Java?
Java packages are collection of classes and interfaces.
Question 18: What is the function of main method in Java?
Main() method is the entry point of all Java programs . The syntax of main is given below
public static void main(String args[])
{
}
Question 19: What is static keyword in Java?
static keyword in Java used to share the value between the objects and it is global in nature.
Question 20: What is the use of instanceof keyword in Java?
instanceof keyword is used to check whether the specified object is an instance of the particular class or not.
It is very important to take a training for Java to get a confidence to attend all interviews. Grooming for an interview would be equipped well when guided by professionals. So to learn more about Java it is always better to get in touch with the best Java training in Kochi or any other cities. There are various Java training institutes are readily available to assist you. The key point is finding the optimal Java online training in Kochi so that you can learn, grow and be experts in your field.
0 notes
Video
youtube
The Pizza Baby SMP is an insane server, from cottagecore aesthetic to microwaves to elections, it gets wild. See how strange this server looks with RTX 3000 series raytracing textures and shaders and even some extremely cursed texture packs and data packs (including Black Ops Cold War Zombies and human beds). And as always, don't forget to "suscribe". (https://bit.ly/tccasanova) Patreon (Support Me, Get Benefits!): https://ift.tt/2IX3SSu Ko-Fi (Support me, without being monthly!): https://ift.tt/2HqfJs1 Twitter: (Pointless Ramblings): https://bit.ly/TwitterCasanova Discord (Chat with me!): https://bit.ly/tcDiscord Subreddit (r/tccasanova): https://bit.ly/Rtccasanova eFuse (Gamer/Streamer World): https://bit.ly/eFuseNova Tellonym (Ask Me Anything!): https://bit.ly/TellonymNova My Tumblr Group (Another place to chat!): https://bit.ly/CasanoviaTumblr My Remind Class (Even tho I barely remember): https://bit.ly/RemindNova ---------- Tags / alternate titles The Pizza Baby SMP is insane The Pizza Baby minecraft SMP is insane The Pizza Baby minecraft Survival Multiplayer is insane The PizzaBaby SMP is insane smplive live lunchclub lunch club dream team dreamsmp epicsmp smpepic lgbt lgbtq trans gay pride pansexual genderfluid bread boie breadboie bread.boie astrostrudels astro strudels irl catboie irl_catboie heaven fib yaomarso smp smp live smplive dream dream team dream team smp dream smp epic matt watson jacksfilms microwave microwave meme minecraft rtx raytracing what type of girl are you microwave be like java resource pack texture pack textures meme dead memes dank cancer cancerous funny hospital despair love voice acting actor voices voicing over overs VA animation art frog frogs frogcore COD Call Of Duty CW Call of Duty bitchy bimbos ---------- Some of my Gaming PC Specs: GPU: GeForce RTX 3060 Ti CPU: Intel(R) Core(TM) i7-9700F CPU @ 3.00GHz Memory: 16 GB RAM (15.94 GB RAM usable) Current resolution: 1920 x 1080, 60Hz ---------- A big thanks to the people who made this video possible: Patrons: (https://ift.tt/2IX3SSu) MEGA FAN! ($20.00+) Brian Charlie Menton Super Big Fan! ($10.00+) Raskolnikov Fan ($3.00+) Radium Ashes Shawn Singleton ---------- People in this video (or mentioned, but in the PizzaBaby SMP): Astrostrudels : https://ift.tt/3sydV2U https://www.youtube.com/channel/UCimmwxOfWGsY8TDkQ4WSaEg https://ift.tt/3oMQX5I Bread.boie / Breadboie / bread boie https://ift.tt/2LWuIM6 https://www.youtube.com/channel/UCjBjg1y3n_NOEMldq-isnOQ https://ift.tt/38Qd0TG yaomarso / fib https://www.youtube.com/user/ScentedGiraffe https://ift.tt/3bRLFCx ---------- The Pizza Baby SMP is a whitelisted Survival Multiplayer Minecraft Server created by astrostrudels. Some players including notfib, breadboie, astrostrudels, and others stream the events of the server on Twitch. ---------- Minecraft is a sandbox video game developed by Mojang. The game was created by Markus "Notch" Persson in the Java programming language. Following several early test versions, it was released as a paid public alpha for personal computers in 2009 before releasing in November 2011, with Jens "Jeb" Bergensten taking over development. Minecraft has since been ported to several other platforms and is the best-selling video game of all time, with 200 million copies sold and 126 million monthly active users as of 2020. In Minecraft, players explore a blocky, procedurally-generated 3D world with infinite terrain, and may discover and extract raw materials, craft tools and items, and build structures or earthworks. Depending on game mode, players can fight computer-controlled "mobs", as well as cooperate with or compete against other players in the same world. Game modes include a survival mode, in which players must acquire resources to build the world and maintain health, and a creative mode, where players have unlimited resources. Players can modify the game to create new gameplay mechanics, items, and assets. Minecraft has been critically acclaimed, winning several awards and being cited as one of the greatest video games of all time. Social media, parodies, adaptations, merchandise, and the annual MineCon conventions played large roles in popularizing the game. It has also been used in educational environments, especially in the realm of computing systems, as virtual computers and hardware devices have been built in it. In 2014, Mojang and the Minecraft intellectual property were purchased by Microsoft for US$2.5 billion. A number of spin-off games have also been produced, such as Minecraft: Story Mode, Minecraft Dungeons, and Minecraft Earth. ---------- #tccasanova #minecraft #rtx #smplive #dreamsmp #smp #epicsmp #smpepic #twitch #breadboie #ColdWar #ColdWarZombies #MinecraftRTX #RTXMiecraft
0 notes
Text
Java Interview Questions
In the tech universe, knowing almost all the necessary scripts is an advantage. One of the essential languages to get hold of is Java, a programming language and computing platform released in 1995 by Sun Microsystems.
Twenty-five years of its existence has only strengthened its prominence in the programming arena. Today, it is used by nearly more than ten million developers across the globe. Hence, learning Java is worth every minute. Srishti Campus is the best Java Training Centre in Trivandrum, Kerala.
Here are top-ten advanced java interview questions that can help you land the job of your choice.
What all platforms does Java support?
It is a fundamental question that can be asked at every interview panel. Java is a language that runs on many platforms. The popular platforms that support Java include Windows, Mac OS, Linux UNIX, etc.
What exactly is Reflection? Explain with its uses.
Java reflections are the runtime API used to inspect and change the behaviour of interfaces, methods, and classes. They help the user to make new objects, get field values, and call methods. It also analyzes classes, fields, interfaces, and methods in runtime. Reflection can also be used by debuggers to examine private members of classes. To learn more about such questions, Srishti Campus is the best online java training centre.
Why is Java an independent platform?
Java is an independent platform because of its ability to run anywhere. In other words, the bytecodes can run on any system despite its underlying operations. Java Training Institution can help aspiring candidates learn more about the program.
What are Daemon Threads in Java?
They are typically like service providers for other threads or objects running as daemon threads. Their importance arises when normal threads are executed, and the threads are otherwise used for background supporting tasks.
What is singleton?
It is a class which permits only a single instance of itself to be created by giving access for its creation. It is primarily used when a user limits instantiation of classes to one subject. It also contains private and unique instances. It can be of immense help when a single object needs to coordinate actions across the system.
What is Java Servlet?
The Java Servlet is a server-side technology designed to facilitate the extension of web servers by providing dynamic response and data persistence.
Why is Java not Object Oriented?
Java is the language that uses eight primitive data types ranging from char, int, char, boolean, float, short, double, long, and byte, and these are not objects.
What does Java Bean mean?
Beans comprise the cardinal scope of the spring framework. It is managed by the Spring IOC container.
How is equals () different from = = in Java?
The Object class in Java defines the Equals() method for comparing two objects defined by business logic. “Equal” or “= =” is a binary operator provided by Java and used to compare primitives and objects. The implementation at the default stage uses the = = operator for the comparison of two objects.
What does multiple inheritance mean? As the name goes, it is a process by which multiple parent class properties are inherited by a child class. It is also known as the diamond problem and is, however, supported by Java.
Srishti Campus provides the best Java training in Trivandrum. Our world-class Java Training will help you to become a Java expert. We offer them the most credible placement assistance and certification guidance for java training in Trivandrum. inter is one of the reputed institutions providing the most competitive learning in Java and other technical courses. We offer the best curriculum prepared through proper research by experts. Become a certified Java Developer with our unique course!!
0 notes
Text
Spring Digging Road 2-> Assembly of SpringBean
# Assembly of SpringBean
##SpringBean allocation plan
Spring container is responsible for creating bean in applications and coordinating the relationships among these objects through dependency injection.
But as a developer, you need to tell Spring which bean to create and how to assemble them together. When describing how bean are assembled, Spring has great flexibility and provides three main assembly mechanisms:
```
1. Implicit bean discovery mechanism-annotation;
2. Explicit configuration in Java -- JavaConfig;
3. Explicit configuration in XML -- XML configuration.
```
###Annotation assembly Bean
Spring realizes automatic assembly from two angles:
```
Component scanning : Spring will automatically discover bean created in the application context
Automatic assembly : Spring automatically satisfies the dependencies between bean.
```
**PS : The combination of component scanning and automatic assembly can minimize explicit configuration.
**
```
1.Create bean that can be discovered
2.Name the bean scanned by the component
3.Set the basic package for component scanning
4.Automatic assembly by adding annotations to bean
```
The directory structure is as follows
First of all, let everyone look at the contents of pom.xml and springConfig.xml on my side, as shown in the figure:
Several ways to annotate Bean assembly
```
Member variable injection
Constructor injection
Setting mode injection
```
Ok, it's time to code.
The following is member variable injection, which mainly adds @Autowire annotation to A to be passed into Class B.
public class SpringTest {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/spring/springConfig.xml");
B b = (B) context.getBean("b");
b.print();
}
}
@Component
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
@Component
class B {
@Autowired
A a;
void print() {
System.out.println("In the method of Class B" + a);
}
}
Then there is constructor injection, at this time, the constructor of B is added @Autowired
public class SpringTest {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/spring/springConfig.xml");
B b = (B) context.getBean("b");
b.print();
}
}
@Component
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
@Component
class B {
A a;
@Autowired
B(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
Finally, set the way to inject. In one method, automatic assembly is performed. The method name can be arbitrary, only @Autowired needs to be added to the method name. here, for the sake of standardization, setA is used as the method name
public class SpringTest {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/spring/springConfig.xml");
B b = (B) context.getBean("b");
b.print();
}
}
@Component
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
@Component
class B {
A a;
@Autowired
void setA(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
###Java code assembly Bean
Although it is a more recommended way to realize automatic configuration of Spring through component scanning and annotation in many scenarios, sometimes the scheme of automatic configuration does not work, so it is necessary to explicitly configure Spring Bean.
For example, when you want to assemble a component in a third-party library into an application, you can't add @Component and @Autowired annotations to its class, so you can't use the automatic assembly scheme.
In this case, explicit configuration must be adopted. There are two alternatives for explicit configuration: JavaConfig and XML, and JavaConfig is a better one because it is more powerful, type-safe and friendly to refactoring. After all, JavaConfig belongs to Java code.
At the same time, JavaConfig is different from other Java codes, which is conceptually different from business logic and domain codes in applications. Although it uses the same language as other components, JavaConfig is the configuration code.
This means that it should not contain any business logic, and JavaConfig should not intrude into business logic code. Although it is not necessary, JavaConfig is usually put in a separate package, which makes it separate from other application logic, so that there is no confusion about its intention.
Several ways of assembling Bean with Java code:
```
Constructor injection
Setting mode injection
```
The first is constructor injection
@Configuration
public class JavaConfigTest {
@Bean
A newA() {
return new A();
}
@Bean
B newB() {
return new B(newA());
}
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaConfigTest.class);
B b = (B) context.getBean("newB");
b.print();
}
}
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
class B {
A a;
B(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
Then setting mode injection
@Configuration
public class JavaConfigTest {
@Bean
A newA() {
return new A();
}
@Bean
B newB() {
B b = new B();
b.setA(newA());
return b;
}
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaConfigTest.class);
B b = (B) context.getBean("newB");
b.print();
}
}
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
class B {
A a;
void setA(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
###Assemble Bean through XML
When Spring first appeared, XML was the main way to describe configuration, but XML was no longer the only alternative way to configure Spring. However, in view of the large number of Spring configuration projects based on XML, it is very important to understand how to assemble Sping projects through XML.
Several ways to assemble Bean through XML
```
Constructor injection
Setting mode injection
```
The first is constructor injection:
Project code is:
public class XMLTest {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/xml/springConfig.xml");
B b = (B) context.getBean("b");
b.print();
}
}
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
class B {
A a;
B(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
springconfig.xml As shown in figure:
Then there is the setting mode injection
Project code is:
public class XMLTest {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/xml/springConfig.xml");
B b = (B) context.getBean("b");
b.print();
}
}
class A {
@Override
public String toString() {
return "introduce Class A";
}
}
class B {
A a;
public void setA(A a) {
this.a = a;
}
void print() {
System.out.println("In the method of Class B" + a);
}
}
springconfig.xml Figure:
###Spring annotation
@Autowired : Automatically assemble member variables, and @Autowired(required=false) will not report an error if no matching Bean can be found.
@Qualifier : Comments specify the ID of the injected bean
@Component : Define a bean
@Controller : Controller
@Service : Define a service bean
@Repository : Used to take the class identity of data access layer (DAO) as a bean
@Scope : Set the type of bean
###Others:
Singleton: In the whole application, only one instance of bean is created :
```
value=ConfigurableBeanFactory.SCOPE_SINGLETON
```
Prototype : A new bean instance is created every time it is injected or acquired through Spring context
```
value=ConfigurableBeanFactory.SCOPE_PROTOTYPEE
```
Request : In a Web application, a bean instance is created for each request :
```
value=WebApplicationContext.SCOPE_REQUEST
```
Session : In a Web application, a bean instance is created for each session
```
value=WebApplicationContext.SCOPE_SESSION
```
0 notes
Link
Ruby is one of the underrated programming languages among modern developers. It has become popular with the Ruby on Rails framework.
Ruby is making developers happy, productive and enjoying programming. - Yukihiro Matsumoto
You are maybe coming from the JS world with a lot of frameworks or from Java and all its complexity. If you are enough of wasting your time building software that matter and want concrete result as soon as possible, let me introduce you to Ruby.
I'll introduce you to the concept of metaprogramming. First time I learned Ruby, my mind literally blew when I was confronted to this.
Think about a program that can generate program itself. A program that can generate executable code without the help of a developer.
No, it's not sci-fi, it's Ruby Metaprogramming !
If I had to explain to a 5 years old, imagine you want to draw a sunny city, you take your pen and write "Sunny City" on the paper. Push the button and magic happens. That's metaprogramming.
Now, I'll explain to real developers.
In Ruby, you can make runtime introspection on method. In another hand, you can ask an object about its capabilities (Do you have this method?), its variables, constants and its class and ancestors.
In this article I'll show you some examples with methods like respond_to? (? is a Ruby convention for method returning a boolean) send and define_method. But there is a lot more like method_missing, remove_method and undef_method. I'll explain these 3 methods and finally show you the mind-blowing examples.
The Respond_to?() Method
This method tests your class if it can handle a specific message, for those who don't speak Ruby: it checks if a method can be called in a specific class.
(In the Ruby vocabulary, message is known as a method).
Here is a Shipment class:
class Shipment def prepare_for_delivery @message = 'Shipment is prepared for delivery' end def tracking_code(code) @tracking_code = code end end
Use the respond_to? method to check if prepare_for_delivery method exists:
s = Shipment.new s.respond_to?(:prepare_for_delivery) ==> true
A more complete example sending a message, if this one exists, to another object.
s = Shipment.new if s.respond_to?(:cancel_shipping) s.cancel_shipping else puts "Oh no ! Shipment cannot be cancel." end
It can be used for any classes.
'hello'.respond_to?(:count) ==> true 'world'.respond_to?(:include) ==> false
Did you catch it?
Well, keep it in mind for the end of this article.
The Send() Method
You can call any method in a class with the send() method.
s = Shipment.new if s.respond_to?(:tracking_code) s.send(:tracking_code, '123ABC') # or s.send('cancel_shipping', '123ABC') else puts "Tracking code is not available." end
(Message is sent in the first parameter of send())
I'm hearing you saying: "Why not calling our method directly ?" Yes, we can and I know that this example is not a real world example on how we use it.
Let's continue.
The Define_method() Method
Now that you know the logic, you could even find the behavior of this method before I explain it to you.
It… defines a method ? Well done !
class Shipment define_method :cancel do |reason| @cancelled = true puts reason end end
You just defined a new method for the Shipment class, setting an instance variable cancelled to true and printing the reason.
Wait, for the final example that will blow your mind.
Metaprogramming In One Example
You know the basics of Ruby metaprogramming, let's see the final example.
Let's embark on the sea trip to metaprogramming and set sail !
# We create a container class. We only store the product's name at instantiation class Container attr :product_name def initialize(name) @product_name = name end end # Apples ! Oranges ! All of theses fruits are contained in FruitContainer extending Container # For simplification we only have one scanner class FruitContainer < Container def apples_scanner puts "Scanning apples..." end end # Potatoes ! Broccoli ! All of vegetables are contained in VegetableContainer extending Container # For simplification we only have one scanner class VegetableContainer < Container def potatoes_scanner puts "Scanning potatoes..." end end # The Cargo containing all the containers class Cargo # The constructor accepting multiple parameters def initialize(*containers) containers.each do |container| # self.class.send is used to define singleton methods for our class # we could also use define_singleton_method self.class.send(:define_method, "inspect_#{container.product_name}") do scanner_name = "#{container.product_name}_scanner" if container.respond_to?(scanner_name) container.send(scanner_name) else puts "No scanner found." end end end end end potatoes_container = VegetableContainer.new "potatoes" apples_container = FruitContainer.new "apples" cargo = Cargo.new(potatoes_container, apples_container) cargo.inspect_apples cargo.inspect_potatoes
We used all the methods I explained. For each Container classes, we define new methods which call a method (if exists) based on their product name, a scanner.
The output:
Scanning apples... Scanning potatoes...
Now, you know what metaprogramming is and how it works. Well done.
One of the first uses case of metaprogramming is creating its own DSL (Domain Specific Languages).
There are some well-known tools based on the Ruby DSL, Chef and Puppet for DevOps peoples.
This is what makes Ruby beautiful.
0 notes