程序员

继承和接口的注入应用

2018-03-19  本文已影响17人  guazi1020

关于注入和装配的应用

1.需求背景

总体要求:员工发送信息

分解需求:用注入的方式将员工发消息的类描述清晰

员工对象(Employee)

image.png

父类:Person

@Entity
public class Person {

    private String Name;
    private String Phone;
    private Date Birthday;
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public String getPhone() {
        return Phone;
    }
    public void setPhone(String phone) {
        Phone = phone;
    }
    public Date getBirthday() {
        return Birthday;
    }
    public void setBirthday(Date birthday) {
        Birthday = birthday;
    }
}

信息操作接口:IInfoManage

public interface IInfoManage {

    /**
     * 信息发送
     */
    public void MessageSend();
    /**
     * 信息删除
     */
    public void MessageDel();
}

员工类:Employee

@Component
//继承Person实现InfoManage方法
public class Employee extends Person implements IInfoManage {

    private String Department;
    private String Station;
    /**
     * 所属部门
     * @return
     */
    public String getDepartment() {
        return Department;
    }
    public void setDepartment(String department) {
        Department = department;
    }
    /**
     * 所属岗位
     * @return
     */
    public String getStation() {
        return Station;
    }
    public void setStation(String station) {
        Station = station;
    }
    @Override
    public void MessageSend() {
        // TODO Auto-generated method stub
        System.out.println("Employee MessageSend");
    }
    @Override
    public void MessageDel() {
        // TODO Auto-generated method stub
        System.out.println("Employee Del");
    }
}

EmployeeSendInfo

//用户发送消息
@Component
public class EmployeeSendInfo {

    private IInfoManage infoManage;
    @Autowired
    public EmployeeSendInfo(IInfoManage infoManage){
        this.infoManage=infoManage;
    }
    
    public void SendInfo(){
        this.infoManage.MessageSend();
    }
}

自动配置类 config.java

@Configuration
@ComponentScan
public class CDConfig {

}

测试

public class test {
    ApplicationContext context=new AnnotationConfigApplicationContext(CDConfig.class);
    @Test
    public void EmployeeSendTest(){
        context.getBean(EmployeeSendInfo.class).SendInfo();
    }
}

最后结果:

image.png
上一篇下一篇

猜你喜欢

热点阅读