为啥我的@Bean设置的init方法不能执行,一直报类型转换错误

来源:4-5 Spring Bean装配之基于Java的容器注解说明——@Bean

Minions

2017-03-02 16:23

//这是我得到Bean容器的类

public class TestSpring {

public static void main(String[]args){

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("testSpring.xml");

/*TestProperty tp = (TestProperty) context.getBean("testPropertity");

TestProperty tp2 = (TestProperty) context.getBean("testPropertity");

System.out.println(tp);

System.out.println(tp == tp2);

Zhujie1 zj = (Zhujie1) context.getBean("zhujie1");

System.out.println(zj);*/

/*String tb = (String) context.getBean("name");

int pass = (int) context.getBean("pass");

System.out.println(tb);

System.out.println(pass);*/

Store tb2 = (Store) context.getBean("testBean2");

System.out.println(tb2.getClass());

context.close();

//这是我的store接口

public interface Store {}

//这是我的实现store的类

public class StringStore implements Store{

public void init(){

System.out.println("This is StringStore de init method");

}

public void destroy(){

System.out.println("This is StringStore's destroy method");

}

}

//这是在bean中设置init与destroy方法的类

@Configuration

public class TestBean2 {

@Bean(name="testBean2",initMethod="init",destroyMethod="destroy")

public Store method(){

return new StringStore();

}

}

//这是错误

Exception in thread "main" java.lang.ClassCastException: com.test.zhujie2.TestBean2$$EnhancerBySpringCGLIB$$9eeb0c76 cannot be cast to com.test.zhujie2.Store

at com.test.Spring.TestSpring.main(TestSpring.java:24)


写回答 关注

1回答

  • 阳光666
    2017-03-03 11:53:52

    我不懂,但是我想问一下,不能被抛到zhujie2.Store中,代码中的zhujie2在哪里


Spring入门篇

为您带来IOC和AOP的基本概念及用法,为后续高级课程学习打下基础

268787 学习 · 963 问题

查看课程

相似问题