案例解析java依赖注入,spring的工厂模式和依赖注入的实例解析(*.ClassNotFoundException)...

//墨盒接口

public interface Ink {

// 获得颜色方法

public String getColor();

}

//彩色墨盒实现类

public class ColorInk implements Ink {

public String getColor() {

// TODO Auto-generated method stub

return "得到财色墨盒";

}

}

//灰色墨盒实现类

public class GreyInk implements Ink {

public String getColor() {

// TODO Auto-generated method stub

return "灰色墨盒";

}

}

墨盒工厂

public class InkFactory2 {

public Ink getInk(String string) {

if (string.equalsIgnoreCase("color")) {

return new ColorInk();

}else {

return new GreyInk();

}

}

}

测试类

public static void main(String[] args) {

InkFactory2 iFactory2=new InkFactory2();

Ink ink=null;

ink= iFactory2.getInk("color");

System.out.println(ink.getColor());

ink= iFactory2.getInk("grey");

System.out.println(ink.getColor());

将工厂模式交给spring管理,通过依靠配置文件,bean的配置实现工厂实例

测试

//通过上下文获得配置文件信息。(此处报错)

ApplicationContext aContext=new

ClassPathXmlApplicationContext("applicationContext.xml");

Ink ink=null;

//通过getbean的方法传参 “color”获得工厂实例。

ink=(Ink) aContext.getBean("color");

System.out.println(ink.getColor());

ink=(Ink) aContext.getBean("grey");

System.out.println(ink.getColor());

然后重点来了,报错,这就是本文另一个目的了.

" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com/pb/ColorInk.java] for bean with name 'color' defined in class path resource [applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: com/pb/ColorInk.java

at

java.lang.ClassNotFoundException: com/pb/ColorInk.java

还有一个疑问:

配置的class 有没有src 有没有java,有什么区别和意义吗,不过不管哪种配置,报错的内容都一样。

然后百般努力,搜索,求助,

正常输出。

这就是. //的区别。一个符号错了的的路径错误。

有位前辈memories告诉我一个方法,推荐给大家

配置文件中有文件名后缀的用/,没有的用.

实在是大赞,明了实用。

还有有谁明确一下这两者的区别以及应用场合吗?

谢谢!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值