将类交给对应的Spring之后,可以使用该类也可以设置其属性,在Spring配置文件当中
<?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"> <!-- Spring入门的配置 --> <!-- id:接口的名称 class:实现类全路径 就将这个类交给Spring管理了 --> <bean id="userDao" class="com.itzheng.spring.demo1.UserDaoImpl"> <property name="name" value="张三"></property> </bean> </beans> package com.itzheng.spring.demo1; /* * 用户管理的业务层实现类 */ public class UserDaoImpl implements UserDao { private String name; public void setName(String name) { this.name = name; } @Override public void save() { // TODO Auto-generated method stub System.out.println("UserService执行了。。。" + name); } } package com.itzheng.spring.demo1; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * Spring的入门 */ public class SpringDemo1 { @Test /* * 传统方式的调用 */ public void demo1() { UserDaoImpl userdao = new UserDaoImpl(); userdao.setName("李四"); userdao.save(); } @Test //Spring的方式的调用 public void demo2() { //创建Spring的工厂(参数是配置文件XML的名称) ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂,解析XML,反射对应类名称,活动对应的对象 UserDao userdao = (UserDao)applicationContext.getBean("userDao"); userdao.save(); } }运行demo2
B 依赖了 A
B 继承了 A
松散 紧密 维护代码重用性。 要理解这一点,请再次使用相同的示例。假设还有另外两个类College和Staff以及上面两个类Student和Address。为了保持学生的地址,学院地址和工作人员的地址,我们不需要一次又一次地使用相同的代码。 我们只需要在定义每个类时使用Address类的引用
class Address { int streetNum; String city; String state; String country; Address(int street, String c, String st, String coun) { this.streetNum=street; this.city =c; this.state = st; this.country = coun; } } class StudentClass { int rollNum; String studentName; //Creating HAS-A relationship with Address class Address studentAddr; StudentClass(int roll, String name, Address addr){ this.rollNum=roll; this.studentName=name; this.studentAddr = addr; } public static void main(String args[]){ Address ad = new Address(55, "Agra", "UP", "India"); StudentClass obj = new StudentClass(123, "Chaitanya", ad); System.out.println(obj.rollNum); System.out.println(obj.studentName); System.out.println(obj.studentAddr.streetNum); System.out.println(obj.studentAddr.city); System.out.println(obj.studentAddr.state); System.out.println(obj.studentAddr.country); } }