跟随小破站学习java spring框架第三天

    技术2022-07-10  106

    spring错误代码及其原因

    public class TestBySpring { public static void main(String[] args) { //1.初始化容器 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = ac.getBean(Person.class); System.out.println(person); } } <?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.xsd"> <bean id="personOne" class="com.atguigu.spring.mod.Person"> <property name="id" value="111"></property> <property name="name" value="李四"></property> </bean> <bean id="personTwo" class="com.atguigu.spring.mod.Person"> <property name="id" value="222"></property> <property name="name" value="小红"></property> </bean> </beans>

     错误原因:.xml文件下有两个person类 系统并不确定调用哪个person类!

    正确的修改方式:

    产生原因:在调用反射方法创建对象时 需要有对象的空参方法

    注:在初始化容器时会产生提示 ac对象没有关闭资源

    解决办法:

    将ac的类换成ClassPathXmlApplicationContext 使用.close()方法 因为在BeanFactory接口的实现目录下处于功能最全面的底层

    IOC是一种思想 DI是IOC的具体实现方式!

     

     

    2种不同的属性注入方式:

    此处name="id" id所使用的是类中的set方法 所以在类中定义属性名时可以不同名 需与括号内调用的id保持命名相同

    构造器注入方式的前提是所使用类中具有构造器方法,数目和类型必须一致 如果不一致报错!

    出现数目一致 类型不相同时 可通过索引+类型定义的方式来赋值!

    Processed: 0.015, SQL: 9