Spring 从零开始-04

接下来主要讲讲自动装配,主要有两种方式,一种是使用xml文件进行,另外一种是使用注解的方式。
先说xml的方式共有四种方式ByName、ByType、constructor、autodectect。
ByName的要求是装配与该类属性名称相同ID的bean

public class User {
    private String name;
    private int age;
    private Education edu;

    public Education getEdu() {
        return edu;
    }

    public void setEdu(Education edu) {
        this.edu = edu;
    }

    public void born(){
        System.out.println("user born");
    }

    public void death(){
        System.out.println("user death");
    }

// public User(String name,int age){
// this.name = name;
// this.age = age;
// } 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
public class Education {
    private String junior;
    private String senior;
    private String college;

    public void selfIntro(){
        System.out.println("初中"+this.junior+"高中"+this.senior+"大学"+this.college);
    }
    public String getJunior() {
        return junior;
    }
    public void setJunior(String junior) {
        this.junior = junior;
    }
    public String getSenior() {
        return senior;
    }
    public void setSenior(String senior) {
        this.senior = senior;
    }
    public String getCollege() {
        return college;
    }
    public void setCollege(String college) {
        this.college = college;
    }

}
public class test {
public static void main(String[] args) {

        // User user = new User();
        // user.setAge(10);
        // System.out.println(user.getAge());
        ApplicationContext ac = new ClassPathXmlApplicationContext("blog4/bean.xml");
        User user = (User)ac.getBean("user");

        System.out.println(user.getName());
        System.out.println(user.getAge());
        user.getEdu().selfIntro();

    }
}
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
     <!-- default-init-method="born" default-destroy-method="death"-->

    <bean id="user" class="blog4.User" autowire="byName">
        <property name="name" value="spirit"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="edu" class="blog4.Education" >
        <property name="junior" value="汉光"></property>
        <property name="senior" value="一中"></property>
        <property name="college" value="西电"></property>
    </bean>




</beans> 

id名称为edu与User类中的的属性名相同。但是这明显会造成一定的限制。
ByType顾名思义就是依照类型来装配,我们更改上面的xml文件

<bean id="user" class="blog4.User" autowire="byType">
        <property name="name" value="spirit"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="education" class="blog4.Education" >
        <property name="junior" value="汉光"></property>
        <property name="senior" value="一中"></property>
        <property name="college" value="西电"></property>
    </bean>

但是如果出现多个可以装配的类型就需要区分了,primary,autowire-candidate两个属性用于区分,primary的默认值是ture,表示的是在装配时首选,所以即使指定primary=”false”依旧会报错啊,但是autowire-candidate取false表示不参与装配

<bean id="education" class="blog4.Education" 
    primary="false" autowire-candidate="false">
        <property name="junior" value="汉光"></property>
        <property name="senior" value="一中"></property>
        <property name="college" value="西电"></property>
    </bean>

    <bean id="educa" class="blog4.Education" >
        <property name="junior" value="邯郸"></property>
        <property name="senior" value="邯郸"></property>
        <property name="college" value="西安"></property>
    </bean>

constructor构造器方法
在user中加入构造方法

public User(Education education){
        this.edu = education;
    }
<bean id="user1" class="blog4.User" autowire="constructor" />

    <bean id="education" class="blog4.Education" 
    primary="false" autowire-candidate="false">
        <property name="junior" value="汉光"></property>
        <property name="senior" value="一中"></property>
        <property name="college" value="西电"></property>
    </bean>

    <bean id="educa" class="blog4.Education" >
        <property name="junior" value="邯郸"></property>
        <property name="senior" value="邯郸"></property>
        <property name="college" value="西安"></property>
    </bean>

autodetect就是首先尝试constructor方法,然后尝试ByType方法

接下来说spring的注解方式,注解方式相对于之前的注入方式有较大的区别,但是主要的思想还是一样的,都是通过注入实现实例化,相对于在xml中编写注入,注解则在Java代码中编写。
首先要在xml文件中加入

<context:annotation-config />

表示使用注解自动装配

public class Guitar implements Instrument {
      public void play() {
        System.out.println("Strum strum strum");
      }
}
public interface Instrument {
    public void play();
}

下面的代码展示了几种不同的@Autowired,构造,setter、自定义方法还可以在属性前直接加@Autowired,同时可以删除setter方法了。@Value(“heheheheeh”)是对属性注入内容,很方便是吧。@Autowired如果无法装配就将会抛出NoSuchBeanDefinitionException,如果允许装配空值那么加入@Autowired(required=false),多个构造器时只有一个构造器可以指定required=ture

public class Instrumentalist implements Performer {
      //<start id="autowire_constructor" />
      @Autowired
      public Instrumentalist(Instrument instrument) {
        this.instrument = instrument;
      }

      //<end id="autowire_constructor" />

      public void perform() throws PerformanceException {
        System.out.print("Playing " + song + " : ");
        instrument.play();
      }
      //可以使用value注解进行装配
      @Value("heheheheeh")
      private String song;
      @Autowired
      private Instrument instrument;

      public void setSong(String song) {
        this.song = song;
      }

      public String getSong() {
        return song;
      }
      @Autowired
      //<start id="autowire_nonsetter" /> 
      public void heresYourInstrument(Instrument instrument) {
        this.instrument = instrument;
      }

      //<end id="autowire_nonsetter" />
      @Autowired
      public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }

    public Instrument getInstrument() {
        return instrument;
      }
    }
public class PerformanceException extends Exception {
    private static final long serialVersionUID = 1L;
}
public interface Performer {
    void perform() throws PerformanceException;
}
public class Piano implements Instrument {

    public void play() {
        System.out.println("PLINK PLINK PLINK");
    }
}

可以看到我吧piano的bean注释了,是因为装配的时候将会出现错误,因为无法确定使用哪个bean进行装配,需要使用@Qualifier(“guitar”)来指定ID为guitar的bean。但是!!!我经过测试还是无法区分,不明白,如果你明白为什么,请告诉我

<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:annotation-config />

<bean id="eddie" class="testAutowire.Instrumentalist">
 <!-- <property name="song" value="Running with the Devil"/> -->  
</bean>

<bean id="guitar" class="testAutowire.Guitar">
</bean>
<!-- <bean id="piano" class="testAutowire.Piano" /> -->
</beans>

下面的代码使用的是junit单元测试,如果不懂查查相关资料,import我加上了,对应着找很方便,还有我第一篇论文中有一个spring的jar里面有(不要积分,赶紧吧!)。另外使用@Inject可以完全取代@Autowired,@Named()=@Qualifier()

import javax.inject.Inject;
import javax.inject.Named;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("beans.xml")

public class AnnotationConfigTest {
  @Autowired
  private Instrumentalist eddie;

  @Autowired
  @Qualifier("guitar")
  private Instrument guitar;

  @Test
  public void shouldWireWithAutowire() {
     System.out.println(eddie.getSong()); 
     eddie.getInstrument().play();
     assertNotNull(eddie.getInstrument());
     assertEquals(guitar, eddie.getInstrument());
  }
}

现在xml文件已经很少了吧,现在来4个标注
@Component 将类注解为bean
@Controller spring MVC 控制
@Repository 数据仓库
@Service 定义服务

除了第一个剩下的到了DAO才会用到,先不做了解也可以。测试的xml文件如下,注意是包的名称

<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="com.autodetect">
  </context:component-scan>
</beans>

代码太多了,不上了,主要上关键的代码,代码会在最后给出。

@Component("eddie")
public class Instrumentalist implements Performer {

这里使用@Component定义某个类为bean,括号内表示的是bean的ID,如果不指定那么将会是类名,全小写。

最后就是,使用Java配置,这样将会把xml文件都会省略!

public class HelloWorld {
private String Message;

public String getMessage() {
    return Message;
}

public void setMessage(String message) {
    Message = message;
}
}
@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloworld(){
        return new HelloWorld();
    }
}

注意得到应用上下文和bean的方法变了。。

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

        helloWorld.setMessage("Hello World!");
        System.out.println(helloWorld.getMessage());    
    }

}

代码地址
http://download.csdn.net/detail/wsrspirit/8868625

你可能感兴趣的:(注解,spring,自动装配,注解装配,java装配)