spring基于注解进行注入(个人记录)

时间:2023-03-09 06:45:49
spring基于注解进行注入(个人记录)

spring的Bean基于注解进行配置,再结合自动装配属性,也就DI,其实说白了就相当于初始化的时候给对象赋初值。

配置文件的过程有些麻烦,记录一下。

基于注解进行配置:

1、在applicationContext.xml中配置注解的支持,

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.annotation1"></context:component-scan>

第一行是声明支持注解,第二行是声明扫描的报名。

2、在Bean中进行配置

Spring2.5 引入使用注解去定义Bean
@Component  描述Spring框架中Bean 

Spring的框架中提供了与@Component注解等效的三个注解:
@Repository 用于对DAO实现类进行标注
@Service 用于对Service实现类进行标注
@Controller 用于对Controller实现类进行标注
***** 三个注解为了后续版本进行增强的.

其实Component Repository Service Controller 都可以对任何类进行注解,这些区别在于对功能划分不同而采用不同的注解,可能框架底层对不同名字注解的实现功能有所有不同,但是我现在觉得就是这样。

@Component(“student”)中可以加一个value,字符串,是这个bean的别名。其他的三个注解类似。


一般Bean用注解配置完了,还想往往DI,在初始化对象的时候就去注入属性,可以用@Value注解,兼任性蛮好,虽然你的字段是Int类型的,但是你在注解里写的还是字符串,spring会自动转换为int,但是如果遇到无法转换的情况,还是会出异常。

3、在test类中使用

这里没有手动进行对象的初始化Student student1 ;,因为@Autowired已经声明了自动装配,由spring框架对对象进行初始化。

package com.annotation1;

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(locations="classpath:applicationContext.xml")
public class Annotation1Test {
    @Autowired
    @Qualifier("student")
    Student student1 ;
    @Test
    public void test1(){
        System.out.println(student1.toString());
    }
}

package com.annotation1;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("student")
public class Student {

    @Value(value = "201305922")
    private String id;
    @Value(value = "huxingyue")
    private String name;
    @Value(value = "23")
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}