Java-Spring例题(2)

Java-Spring例题(2)

Java-Spring例题(2)_第1张图片

Java-Spring例题(2)_第2张图片

annotation.dao包下的Leg.java

package annotation.dao;

public interface Leg {
    public void run();
}

annotation.dao包下的LegImpl.java

package annotation.dao;

import org.springframework.stereotype.Repository;

//配置一个bean,相当于。
@Repository
public class LegImpl implements Leg{

    @Override
    public void run() {
        // TODO Auto-generated method stub
         System.out.println("健步如飞");
    }
}

annotation.service包下的 People.java

package annotation.service;

public interface People {
    public void run();
}

annotation.service包下的 PeopleImpl.java

package annotation.service;

import annotation.dao.Leg;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

//配置一个bean,相当于。
@Service("peopleimpl")
public class PeopleImpl implements People{
//    自动根据类型注入。
    @Autowired
    private Leg l;
    
    public PeopleImpl(Leg l){
        this.l=l;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
         l.run();
         System.out.println("People 构造方法 注入 leg");
    }
}

annotation.service包下的 PeopleImpl1.java

package annotation.service;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import annotation.dao.Leg;

//配置一个bean,相当于。
@Service("peopleimpl1")
public class PeopleImpl1 implements People {
    @Autowired
    private Leg l1;

    public void setL1(Leg l1) {
        this.l1 = l1;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
         l1.run();
         System.out.println("People setter方法 注入 leg");
    }
}

test包下的TestPeople.java

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.service.People;

public class TestPeople {
    public static void main(String[] args) {
        ApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
        People p=(People)appCon.getBean("peopleimpl");
        p.run();
        People p1=(People)appCon.getBean("peopleimpl1");
        p1.run();
    }
}

annotationContext.xml




    
    
      
    

你可能感兴趣的