Spring框架个人问题汇总(持续更新)

来源:互联网 发布:外国人中国菜知乎 编辑:程序博客网 时间:2024/06/06 01:37
###java.lang.ClassCastException: com.xzy.springtest.helloworld.Test cannot be cast to com.xzy.springtest.alice.Test###

出现此问题目前发现的原因有两个:

1.创建的applicationContext.xml中有bean重复的ID值;

ps:不同的xml文件中也不可以相同

2.类中所用功能类导包不正确

org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.xzy.springtest.create.Test]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.xzy.springtest.create.Test.

1.没有找到该类的默认构造方法;即你定义了含参的构造方法但是没有定义无参构造方法

更改bean对象创建创建的时间利弊

如果在bean中添加lazy-init=“default/false/true”属性则可以对bean对象创建的时间进行控制
* default/false:默认bean在创建Spring容器时进行对象的创建
* true:则会在context.getBean时才会创建对象
第一种情况可以在启动Spring容器的时候检查Spring容器配置文件的正确性,再结合tomcat,如果Spring容器不能正常启动,整个tomcat就不能启动。但是这样的缺点是把一些bean过早的放在了内存当中,如果有数据,对内存来说是一个消耗。
第二种情况下可以减少内存的消耗,但是不容易发现错误

Spring的bean对象作用域

所创建的对象默认为singleton(单例),可以通过bean中的scope =“singleton/prototype/request/session/global session”修改对象的作用域。singleton单例,prototype原型(多例),request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效,session作用域表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效,global session作用域类似于标准的HTTP Session作用域

SpringDI赋值

1.set方法:在该属性所在类的applicationContext.xml文件中,该类所在bean下利用property标签进行赋值
基本数据类型:

<property name="id" value="1"></property>

引用数据类型String:

<property name="str" value="1"></property>

List或者Set集合:

<property name="set">        <set>            <value>set1</value>            <ref bean="student"/>//当集合中的数据为对象时        </set></property>

Map集合:

<property name="map">        <map>            <entry key="1">                <value>1</value>            </entry>            <entry key="2">                <ref bean="student"/>//当集合中的数据为对象时            </entry>        </map></property>

properties文件:

<property name="p">        <props>            <prop key="prop1">123123</prop>        </props></property>

2.利用构造方法给属性赋值

<bean id="dog" class="com.xzy.testspring.dto.Dog"> <constructor-arg index="0" value="123"></constructor-arg> <constructor-arg index="1" value="321"></constructor-arg></bean>

ps:index属性为类中定义的第几个变量,第一个为0。使用前提:必须含有对应参数数量的构造方法而此时,就算不定义无参构造方法也是可以运行程序。即未定义constructor-arg时。调用默认无参构造方法定义constructor-arg则该元素确定唯一构造函数

原创粉丝点击