Java-Spring例题(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,相当于<bean id="" class="">。@Repositorypublic 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,相当于<bean id="peopleimpl" class="">。@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,相当于<bean id="peopleimpl1" class="">。@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("annotationContext.xml"); People p=(People)appCon.getBean("peopleimpl"); p.run(); People p1=(People)appCon.getBean("peopleimpl1"); p1.run(); }}
annotationContext.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="annotation"/> <!--开启注解的反对--> <context:annotation-config/></beans>