Here, i am going to describe a reusable jFrame class, which can be used as substitute of standard console output.
Resuable JFrame CODE:
Java-Opening a URL in default browser with start utility in windows
Java-Opening a URL in default browser with start utility in windows
String cmd = "cmd.exe /c start ";
String file = "http://www.google.com";
Runtime.getRuntime().exec(cmd + file);
Dependency Injection with Java Spring IoC, A Complete Example
In this post, I’m going to show you how to
wire together a simple calculator application using Spring’s Dependency Injection. If you need a refresher on the core concepts, take a look at my earlier article "Understanding Dependency Injection and Its Importance".
The application defines three roles: a Reader that supplies two numbers, an Operation that performs some arithmetic on them, and a Writer that outputs the result. By coding to interfaces, we can swap the concrete implementations (e.g., console vs. file, addition vs. multiplication) without touching the business logic. Spring’s IoC container handles the wiring for us.
Reader Interface:
public interface Reader {
Operands readValues(String promptMsg);
}
A concrete implementation that reads from the console:
ConsoleReader:
public class
ConsoleReader implements Reader{
Operands oprnds;
Scanner sc;
public ConsoleReader (){
oprnds=new Operands();
sc=new Scanner(System.in);
}
public Operands readValues(String promptMsg) {
System.out.println(promptMsg);
oprnds.setOp1(sc.nextLong());
oprnds.setOp2(sc.nextLong());
return oprnds;
}
}
The Operation Interface
public interface Operation {
Result operate(long op1,long op2);
String getOperationName();
}
We’ll provide two implementations – multiplication and addition.
Multiply:
public class Multiply implements Operation {
Result res;
public Multiply(){
res=new Result();
}
public Result operate(long op1, long op2) {
res.setRes(op1*op2);
return res;
}
public String getOperationName() {
return "Multiply";
}
}
Addition:
public class Add implements Operation {
Result res;
public Add(){
res=new Result();
}
public Result operate(long op1, long op2) {
res.setRes(op1+op2);
return res;
}
public String getOperationName() {
return "Add";
}
}
The Writer Interface
public interface Writer {
void write(Result res);
}
We’ll create a console writer and a text-file writer so you can see how easily the output destination can be changed.
ConsoleWriter:
public class
ConsoleWriter implements Writer{
public void write(Result
res) {
System.out.println("The result after
operation : "+res.getRes());
}
}
TXTFileWriter:
public class
TXTFileWriter implements Writer{
File file;
PrintWriter fwriter;
public TXTFileWriter(){
try {
file = new File("output.txt");
fwriter = new PrintWriter(
new BufferedWriter( new FileWriter(file)));
} catch (Exception ex) {
System.err.println(ex);
}
}
public void write(Result
res)
{
fwriter.println(res.getRes());
fwriter.close();
}
}
The Model Classes
The
Operands class simply holds two long values with getters and setters. Result wraps a single long value in the same way. I’m showing the essential fields; add getters/setters as needed.
Operands
public class Operands {
private long op1;
private long op2;
//setters and
getters
}
The Result Class
public class Result {
private long res;
//setters and getters
}
Now create a Spring configuration file named
confBean.xml in the classpath (e.g., in the src folder). This file tells the IoC container how to instantiate our beans.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="operation"
class="com.gt.spring.operation.Add"/>
<bean id="reader" class="com.gt.spring.reader.ConsoleReader"/>
<bean id="writer"
class="com.gt.spring.writer.ConsoleWriter"/>
<beans>
Dependency injection wires these beans together at runtime. In the
Main class, we load the context and ask for each bean by its id – no new keyword in sight.
public class Main {
public static void
main(String[] args) {
ApplicationContext ctx =
new
ClassPathXmlApplicationContext("confBean.xml");
//get beans from ctx
Reader rdr = (Reader) ctx.getBean("reader");
Operation opr = (Operation)ctx.getBean("operation");
Writer wrt = (Writer) ctx.getBean("writer");//
//read operands
Operands opnds = rdr.readValues("Enter
the Values :");
//do operation
Result res =opr.operate(opnds.getOp1(), opnds.getOp2());
//write result
wrt.write(res);
}
}
Dependency Injection in Java without Spring IoC Framework........ How it is possible... A Simple way
You can first read Understanding Dependency Injection and its Importance, before this post for clearing Funda of Dependency Injection.
How can we this do programmatically.
rotate();
applyBreak();
}
//override and define
}
class NepaleseRubberWheel implements Wheel{
//override and define
}
// Create Wheel object
Wheel wheelToRun =(Wheel) (Class.forName(wheelToInject).newInstance());
// Execute methods of the wheel object.
wheelToRun.rotate();
wheelToRun.applyBreak();
This works for any implementation of Wheel. To change the Wheel on the Car just change name of Implementation on the txt file.
How can we this do programmatically.
- Create a interface Wheel.
rotate();
applyBreak();
}
- Create implementations
//override and define
}
class NepaleseRubberWheel implements Wheel{
//override and define
}
- Create a txt file, where you write the valid name(say NepaleseRubberWheel ) of a Implementation of Wheel
- Read the txt file
- And finally, to Dynamically load the NepaleseRubberWheel as instance of Wheel;
// Create Wheel object
Wheel wheelToRun =(Wheel) (Class.forName(wheelToInject).newInstance());
// Execute methods of the wheel object.
wheelToRun.rotate();
wheelToRun.applyBreak();
This works for any implementation of Wheel. To change the Wheel on the Car just change name of Implementation on the txt file.
Understanding Dependency Injection and its Importance, A tutorial
Understanding Dependency Injection and its Importance
Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.For example, consider a `Car` object.
A `Car` depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the `Car` object.
Without Dependency Injection (DI):
class Car{
private Wheel wh = new NepaliRubberWheel();
private Battery bt = new ExcideBattery();
//The rest
}
Here, the `Car` object *is responsible for creating the dependent objects.*
What if we want to change the type of its dependent object - say `Wheel` - after the initial `NepaliRubberWheel()` punctures?
We need to recreate the Car object with its new dependency say `ChineseRubberWheel()`, but only the `Car` manufacturer can do that.
Then what does the `Dependency Injection` do for us...?
When using dependency injection, objects are given their dependencies *at run time rather than compile time (car manufacturing time)*.
So that we can now change the `Wheel` whenever we want. Here, the `dependency` (`wheel`) can be injected into `Car` at run time.
After using dependency injection:
Here, we are **injecting** the **dependencies** (Wheel and Battery) at runtime. Hence the term : *Dependency Injection.* We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed. class Car{
private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime
private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime
Car(Wheel wh,Battery bt) {
this.wh = wh;
this.bt = bt;
}
//Or we can have setters
void setWheel(Wheel wh) {
this.wh = wh;
}
}
The advantages/benefits of dependency injection are:
- decoupling the creation of an object (in another word, separate usage from the creation of object)
- ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)
- promotes "Code to interface not to an implementation" principle
- ability to create and use mock dependency during a test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)
Understanding Importance of Interface, Inheritance...... OOP concepts in a different way !
Lets talk about some fundamentals of Object Oriented Design concepts in a different way...
1.IS A - Inheritance
A super class for Animal
Creating Cow class, a type of Animal
In the example above,
Cow is a subclass of Animal because Cow inherits from Animal. So inheritance is ISA relationship. You see the walk() methods is already defined for Animal and we don't need to defined them again and again.
2. Has A - Member Field
Lets create Brain...
Adding brain to Dogs' head.
Dog is obvioulsy an Animal and a Dog has some Memory called dogMemory. Hence, HAS-A relation is defined by a member field.
3. Performs - Interface
Lets introduce a interface IHelp.
Creating A Dog
Here Dog is an Animal, it has Memory and it can Help. We can ensure a Dog can help by implementing IHelp interface.
Something More
The benefit of IHelp interface is that we can get help from all Animals by using same interface methods.
For example , lets create a Horse Class
Getting help from Horse
and for getting help from Dog
You see we can get help from these Animals from same method doHelp();.
Its the fun of Object Oriented Design.......
Enjoy !!!!!
1.IS A - Inheritance
A super class for Animal
class Animal {
int legs;
String name;
public Animal(int legs, String name) {
this.legs = legs;
this.name = name;
}
public void walk() {}
}
Creating Cow class, a type of Animal
class Cow extends Animal {
public Cow(int legs, String name) {
super(legs, name);
}
} In the example above,
Cow is a subclass of Animal because Cow inherits from Animal. So inheritance is ISA relationship. You see the walk() methods is already defined for Animal and we don't need to defined them again and again.
2. Has A - Member Field
Lets create Brain...
class Memory {
int size;
public void loadIntoMemory(Object anything) {}
public boolean isInMemory(Object suspect) {
return true;
}
} Adding brain to Dogs' head.
class Dog extends Animal{
Memory dogMemory;
}Dog is obvioulsy an Animal and a Dog has some Memory called dogMemory. Hence, HAS-A relation is defined by a member field.
3. Performs - Interface
Lets introduce a interface IHelp.
interface IHelp {
void doHelp();
} Creating A Dog
class Dog extends Animal implements IHelp {
private Memory dogMemory;
public Dog(int legs, String name) {
super(legs, name);
}
@Override
public void doHelp() {
if (dogMemory.isInMemory(new Object())) {
walk();
findSuspect();
}
}
private void findSuspect() {}
}
Here Dog is an Animal, it has Memory and it can Help. We can ensure a Dog can help by implementing IHelp interface.
Something More
The benefit of IHelp interface is that we can get help from all Animals by using same interface methods.
For example , lets create a Horse Class
class Horse extends Animal implements IHelp{
public Horse(int legs, String name){
super(legs,name);
}
@Override
public void doHelp() {
carryHuman();
}
private void carryHuman();
}
Getting help from Horse
Horse aHorse= new Horse(4,"Acorn");
horse.doHelp();
and for getting help from Dog
Dog aDog= new Dog(4,"Puppy");
aDog.doHelp();
You see we can get help from these Animals from same method doHelp();.
Its the fun of Object Oriented Design.......
Enjoy !!!!!
Subscribe to:
Posts
(
Atom
)