applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--1.创建spring控制的资源-->
<!-- <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<!–3.将要注入的引用类型的变量通过property属性进行注入,对应的name是要注入的变量名,使用ref属性声明要注入的bean的id–>
<property name="userDao" ref="userDao"/>
<property name="num" value="666"/>
<property name="version" value="itheima"/>
</bean>-->
<!--2.将要注入的资源声明为bean-->
<bean id="userDao" class="com.itheima.Dao.impl.UserDaoImpl">
<constructor-arg index="2" value="123"/>
<constructor-arg index="1" value="root"/>
<constructor-arg index="0" value="com.mysql.jdbc.driver"/>
</bean>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<!--使用构造方法进行注入,需要保障注入的属性和bean中定义的属性一致
一致指顺序一致或类型一致或使用index来解决此问题-->
<constructor-arg name="userDao" ref="userDao"/>
<constructor-arg name="num" value="6666"/>
<constructor-arg name="version" value="itcast"/>
</bean>
</beans>
package com.itheima.Dao.impl;
import com.itheima.Dao.UserDao;
public class UserDaoImpl implements UserDao {
private String username;
private String pwd;
private String driver;
public UserDaoImpl(String driver,String username, String pwd) {
this.driver=driver;
this.username = username;
this.pwd = pwd;
}
public void save() {
System.out.println("user dao running...."+username+" "+pwd+" "+driver);
}
}
package com.itheima.Dao;
public interface UserDao {
public void save();
}
import com.itheima.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserApp {
public static void main(String[] args) {
//2.加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//3.获取资源
UserService userService = (UserService) ctx.getBean("userService");
userService.save();
}
}