Spring使用笔记(一)Bean装配

Bean装配

Spring提供了3种装配机制:

1)隐式的Bean发现机制和自动装配

2)在Java中进行显示装配

3)在XML中进行显示装配

一)自动化装配

1.指定某类为组件类:

@Component
public class Dog {
    private String name = "Jerry";
    //省略getter/setter
}
public interface Person {
    void introduce();
}
//表明该类会作为组件,告知Spring为该类创建bean
//该组件的默认id为:student
@Component
//@Component("aStudent") 为该bean指定id:aStudent
//当然也可以使用Java依赖注入规范:
//@Named("aStudent")
public class Student implements Person{
    @Autowired
    private Dog dog;
    private String name = "Tom";
    private int age = 6;
    private String school = "Happy School";

    public Student() {
    }
    public Student(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

    public void introduce() {
        System.out.println("My name is " + name + ", I'm " + age +
        " years old. I'm from " + school + " !");
        System.out.println("I have dog named " + dog.getName());
    }
    //省略getter/setter
}

2.创建配置类启用组件扫描

1)通过Java配置:

@Configuration
//@ComponentScan 启用组件扫描功能,此时是扫描该类所在包下的所有组件类
@ComponentScan("beans") //设置要扫描的包
//@ComponentScan(basePackages = "beans") 同上
//@ComponentScan(basePackages = {"a", "b", "c"}) 扫描多个包
//@ComponentScan(basePackageClasses = {a.class, b.class, c.class}) 扫描class所在包
public class PersonConfig {
}

2)通过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="beans"/>
</beans>

3.测试: 

//该注解创建了Spring应用上下文
@RunWith(SpringJUnit4ClassRunner.class)
//加载配置
@ContextConfiguration(classes = PersonConfig.class)
public class PersonTest {
    //@Autowired(required = false) 设置为false没有匹配bean时不抛出异常
    @Autowired //当然该注解也可用于方法
    Person student;
    @Test
    public void say() {
        student.introduce();
        //My name is Tom, I'm 6 years old. I'm from Happy School !
        //I have dog named Jerry
    }
}

二)通过Java装配

public class Father implements Person{
    private Student student;
    public Father(Student student) {
        this.student = student;
    }
    public void introduce() {
        System.out.println("I'm " + student.getName() + "'s father.");
    }
}
@Configuration
public class PersonConfig {
    @Bean
    public Dog dog() {
        Dog dog = new Dog();
        dog.setName("Flex");
        return dog;
    }
    
    @Bean //告诉Spring返回的对象注册为Spring应用上下文的bean
    //@Bean(name = "aName") 修改默认名字
    public Student getStudent(){
        Student student = new Student("Jimmy", 22, "Sad School");
        student.setDog(dog());
        return student;
    }
    
    //此处注解会拦截getStudent()方法,传入Spring创建的单例
    @Bean
    public Father getFather() {
        return new Father((Student) getStudent());
    }

    //通过这种方法引用其他bean是最佳方式
    //因为它不要求将person声明到同一配置文件中
    public Person father(Person person) {
        return new Father((Student) person);
    }
}
@Autowired 
Student student;
@Autowired
Father father;
@Test
public void say() {
    student.introduce();
    father.introduce();
    /*My name is Jimmy, I'm 22 years old. I'm from Sad School !
      I have dog named Flex
      I'm Jimmy's father.*/
}

三)通过XML装配

 PersonTest-contxt.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean class="beans.Book" id="book1">
        <property name="bookName" value="YellowBook"/>
    </bean>
    <bean class="beans.Book" id="book2">
        <property name="bookName" value="GreenBook"/>
    </bean>
    <bean class="beans.Dog" id="dog">
        <!--属性注入必须提供相应的属性set方法-->
        <property name="name" value="小白"/>
    </bean>
    <bean class="beans.Student" id="student">
        <property name="dog" ref="dog"/>
        <constructor-arg value="Harry"/>
        <constructor-arg value="28" />
        <constructor-arg value="Killer School"/>
        <property name="books">
            <list>
                <ref bean="book1"/>
                <ref bean="book2"/>
            </list>
        </property>
    </bean>
    <bean class="beans.Father" id="father">
        <constructor-arg ref="student" />
    </bean>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // @ContextConfiguration(locations = { "classpath*:/spring1.xml", "classpath*:/spring2.xml" }) 
public class PersonTest {
    @Autowired
    Student student;
    @Autowired
    Father father;
    @Test
    public void say() {
        student.introduce();
        father.introduce();
       /* My name is Harry, I'm 28 years old. I'm from Killer School !
          I have dog named 小白
          I have 2 books.
          I'm Harry's father.*/

    }
}

四)导入混合配置

1.在JavaConfig导入其他JavaConfig 

@Import(AnotherConfig.class)
@Import({One.class, Tow.class})

2.在JavaConfig中导入xml配置

@ImportResource("classpath: one.xml")

3.在xml中导入其他xml

<import resoune="one.xml">

注意并没有XML能导入JavaConfig

猜你喜欢

转载自www.cnblogs.com/Shadowplay/p/10074681.html