举例:
package com.spring.dao.Impl;
import com.spring.dao.UserDao;
public class TestDaoImpl implements UserDao {
private String name;
private int age;
public TestDaoImpl(){
}
public TestDaoImpl(String name){
this.name=name;
}
public TestDaoImpl(int age){
this.age=age;
}
public void save() {
System.out.println("name---"+name+",age----"+age);
}
}
测试类:
package com.spring.demo;
import com.spring.dao.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("testDao");
userDao.save();
System.out.println(userDao);
}
}
xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--<context:component-scan base-package="com.annocation"></context:component-scan>-->
<bean id="testDao" class="com.spring.dao.Impl.TestDaoImpl">
<constructor-arg name="name" value="李白"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>
</beans>
以上配置文件这么写会出现找不到对应的构造方法,在配置文件中使用构造方式注入,有几个name参数,spring容器就会去找该类字节码文件里的有几个参数的构造方法。并不是一个构造方式对应一个构造方法。