春季启动@Autowired vs动态多态性在松散的耦合时?
嗨,我想这个问题很基本,但请帮忙!!!
假设我有一个接口写作,
public interface Write {
public void writeSomething();
}
public class Pen implements Write {
@Override
public void writeSomething() {
System.out.println("Writing using Pen!!");
}
}
public class Pencil implements Write {
@Override
public void writeSomething() {
System.out.println("Writing using Pencil!!");
}
}
public class Test1 {
public static void main(String[] args) {
Write wr = new Pen();
wr.writeSomething();
}
}
public class Test2 {
@Autowired
@Qualifier("Pen")
private static Write wr;
public static void main(String[] args) {
wr.writeSomething();
}
}
现在有2个实现班级和铅笔,
test2类实施 spring启动的 test1类实施 ,就而言是java中的松散耦合 。
那么@Autowired 的好处是什么?
Hi I guess this question is quite basic but please help out!!!
Let say I have one interface Write and 2 implementing classes Pen and Pencil
public interface Write {
public void writeSomething();
}
public class Pen implements Write {
@Override
public void writeSomething() {
System.out.println("Writing using Pen!!");
}
}
public class Pencil implements Write {
@Override
public void writeSomething() {
System.out.println("Writing using Pencil!!");
}
}
public class Test1 {
public static void main(String[] args) {
Write wr = new Pen();
wr.writeSomething();
}
}
public class Test2 {
@Autowired
@Qualifier("Pen")
private static Write wr;
public static void main(String[] args) {
wr.writeSomething();
}
}
Now,
How does Test2 class implementation of spring boot is better then Test1 class implementaion, in terms of loose coupling in java.
And what is the benefit of @Autowired then ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Autowired
注释创建一个单个Object(bean)
,您的应用程序重复使用而不是每次创建新对象。The
@Autowired
annotation create a singleObject(Bean)
that your application reused instead of creating new Object each time.这是固体依赖性反转的第五个原理。您需要使用接口,并且不要使用实现。
优点之一是创建Test2时,您可以管理将使用的实现。例如,您可以同时创建新的Test2(PEN)或新的Test2(Pencil)取决于您的要求。Spring将使用任何作者实现创建Test2。但是使用Test1,您无法管理作者实现。
此外,它也有可能使用Writer模拟来轻松测试2。
@Autowired将向作者bean注入test2 bean。您必须在test2类上方添加@component或@service注释,或使用@configuration在类中创建test2 bean配置。
This is the fifth principle of SOLID - Dependency inversion. You need use interfaces, and don't use implementations.
One of advantages is when you create Test2 you can manage which implementation you will use. For example you can create both new Test2(Pen) or new Test2(Pencil) dependent on your requirements.Spring will create Test2 with any Writer implementation. But with Test1 you can't manage Writer implementation.
Also it gives possibility to easy test Test2 with Writer mocks.
@Autowired will inject Writer bean into Test2 bean. You have to add @Component or @Service annotation above Test2 class or create Test2 bean configuration in class with @Configuration.