首頁  >  文章  >  Java  >  詳解Spring框架註解的用法程式碼實例

詳解Spring框架註解的用法程式碼實例

黄舟
黄舟原創
2017-03-18 10:36:251782瀏覽

寫在前面:

眾所周知,在JavaEE開發框架中,Spring框架是用的最多的,註解在框架的定位也就越來越明顯了。說句玩笑:能用一個註解解決的,絕不用一堆設定和程式碼解決;如果不能解決,那麼來兩個註解;(穩住,別噴…)

1.@Component是Spring定義的一個通用註解,可以註解任何bean。

2.@Scope定義bean的作用域,其預設作用域是”singleton”,除此之外還有prototype,request,session和global session。

案例:@Component與@Scope用法分析:

BeanAnnotation類別:

@Scope
@Component
public class BeanAnnotation {

    public void say(String arg) {
        System.out.println("BeanAnnotation : " + arg);
    }

    public void myHashCode() {
        System.out.println("BeanAnnotation : " + this.hashCode());
    }

}

junit4測試類別→TestBeanAnnotation類別:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase {

    public TestBeanAnnotation() {
        super("classpath*:spring-beanannotation.xml");
    }

    @Test
    public void testSay() {
        BeanAnnotation bean = super.getBean("beanAnnotation");
        bean.say("This is test.");
    }

    @Test
    public void testScpoe() {
        BeanAnnotation bean = super.getBean("beanAnnotation");
        bean.myHashCode();
        bean = super.getBean("beanAnnotation");
        bean.myHashCode();
    }

}

Spring設定檔→spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>

我們先從Spring設定檔分析,base- package="com.beanannotation"說明我們只處理這個包名下面的註解。

然後分析BeanAnnotation類,有一個say的方法。假設我們不清楚這是一個什麼類型(註:Service或DAO)的類,我們可以用一個通用的註解@Component。

最後分析TestBeanAnnotation類,testSay方法裡super.getBean("beanAnnotation")是從IOC的容器中取到這個bean,並且呼叫bean的say方法。

提出問題的時間到了,當我們super.getBean的時候是透過bean的id從IOC容器中取得的,那麼這個id是什麼呢?因為在我們加入@Component到BeanAnnotation類別上的時候,預設的id為beanAnnotation。如果指定了@Component的名稱,譬如指定為@Component(”bean”)的時候,在單元測試的時候就必須把super.getBean得到的id與之相對應才能測試成功。

在這裡我把@Scope註解單獨分離出來分析,在TestBeanAnnotation類別裡面有一個testScpoe方法。在BeanAnnotation類別裡面有一個myHashCode方法,可能大家有點疑惑,為什麼要用this.hashCode()?因為@Scope指定的是bean的作用域,為了確保測試類別的結果準確明了,所以採用哈希碼值來判斷是否為同一個物件

3.@Repository、@Service、@Controller是更具針對性的註解。

PS:這裡我們需要明白這三個註解是基於@Component定義的註解哦:

①、@Repository通常用於註解DAO類,也就是我們常說的持久層。
②、@Service通常用來註解Service類,也就是服務層。
③、@Controller通常用於Controller類,也就是控制層(MVC)。

4.@Autowired理解為「傳統」的setter方法,可以用在setter方法上,也可以用在建構器或成員變量,能夠進行Spring Bean的自動組裝。

案例:@Autowired用法分析一:

Spring設定檔→spring-beanannotation.xml:

<context:component-scan base-package="com.beanannotation"></context:component-scan>

#SimpleMovie Lister類別:

public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Autowired(required=false)
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

}

在預設的情況下,如果找不到合適的bean將會導致autowiring失敗拋出例外,我們可以將@Autowired註解在這個set方法上,標記required=false來避免。但是,這不是一個必須的,如果找不到movieFinder的實例,是不會拋出異常的,只有在使用的時候發現movieFinder為null,在這種情況下,就要求我們在使用的時候,先判斷movieFinder是不是為null,如果就會報空指標異常。

值得注意的是,我們知道每個類別可以有很多個建構器,但是在使用@Autowired的時候,有且只能有一個建構器能夠被標記為required=true(註:required的預設值為false)。

案例:@Autowired用法分析二:

BeanImplOne類別:

@Order
@Component
public class BeanImplOne implements BeanInterface {

}

BeanImplTwo類別:

@Order
@Component
public class BeanImplTwo implements BeanInterface {

}

BeanInterface類別:

public interface BeanInterface {

}

BeanInvoker類別:

@Component
public class BeanInvoker {

    @Autowired
    private List<BeanInterface> list;

    @Autowired
    private Map<String, BeanInterface> map;

    public void say() {
        if (null != list && 0 != list.size()) {
            for (BeanInterface bean : list) {
                System.out.println(bean.getClass().getName());
            }
        } else {
            System.out.println(" list is null !");
        }

        if (null != map && 0 != map.size()) {
            for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "      " + entry.getValue().getClass().getName());
            }
        } else {
            System.out.println("map is null !");
        }
    }
}

測試類別TestInjection:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {

    public TestInjection() {
        super("classpath:spring-beanannotation.xml");
    }

    @Test
    public void testMultiBean() {
        BeanInvoker invoker = super.getBean("beanInvoker");
        invoker.say();
    }

}

首先,我们清楚BeanImplOne类和BeanImplTwo类是实现了BeanInterface接口的,在BeanInvoker类里面我们定义了list和map,我们通过@Autowired注解把BeanImplOne类和BeanImplTwo类注解进入其中。那么怎么证实是@Autowired注解把这两个类注入到list或者map中的呢?那么请看if循环语句和foreach循环打印,通过这个逻辑判断,如果能够打印出BeanImplOne类和BeanImplTwo类的路径名,就说明这样是可以的。如果有些小伙伴可能不信,那么可以试着不使用@Autowired注解,看结果怎么样。

测试类没有什么好说的,各位小伙伴有没有注意到@Order注解呢?这里需要解释的就是,如果在@Order注解里面输入执行的数字,比如1或者2,那么打印出来的路径名就会按顺序,也就是说通过指定@Order注解的内容可以实现优先级的功能。

5.@ImportResource注解引入一个资源,对应一个xml文件

6.@Value注解从资源文件中,取出它的key并赋值给当前类的成员变量

案例:@ImportResource和@Value用法分析:

MyDriverManager类:

public class MyDriverManager {

    public MyDriverManager(String url, String userName, String password) {
        System.out.println("url : " + url);
        System.out.println("userName: " + userName);
        System.out.println("password: " + password);
    }

}

config.xml:

<context:property-placeholder location="classpath:/config.properties"/>

StoreConfig类:

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean
    public MyDriverManager myDriverManager() {
        return new MyDriverManager(url, username, password);
    }

这个案例我们使用注解配置jdbc数据库的连接,首先创建一个内含构造器的MyDriverManager类,然后配置config.xml里面的资源文件路径,以便@ImportResource注解获取,最后配置StoreConfig类。(注意url、username、password也必须要和数据库的保持一致哦)

详解StoreConfig类:首先我们定义三个成员变量,然后给每一个成员变量打上一个@value注解,注意@value里面的内容一定是资源文件里面的key值。这里的@ImportResource注解就是指明一个资源文件,在这个资源文件里面获取到对应的数据。那么@Configuration注解是用来干嘛的呢?为什么不用@Component注解呢?其实是这样的,@Component注解用于将所标注的类加载到 Spring 环境中,这时候是需要配置component-scan才能使用的,而@Configuration注解是Spring 3.X后提供的注解,它用于取代XML来配置 Spring。

7.@Bean注解用来标识配置和初始化一个由SpringIOC容器管理的新对象的方法,类似XML中配置文件的d7de7346c94b9644ec904d605d4c96bf

ps:默认的@Bean注解是单例的,那么有什么方式可以指定它的范围呢?所以这里才出现了@Scope注解

8.@Scope注解,在@Scope注解里面value的范围和Bean的作用域是通用的,proxyMode的属性是采用哪一种的单例方式(一种是基于接口的注解,一种是基于类的代理)

案例:@Bean和@Scope用法分析:

    @Bean
    @Scope(value ="session",proxyMode = "scopedProxyMode.TARGET_CLASS")
    public UserPreferences userPreferences(){
        return new userPreferences();
    }

    @Bean
    public service userService(){
        UserService service =new SimpleUserService();
        service.setUserPreferences(userPreferences);
        return service;
    }

以上是詳解Spring框架註解的用法程式碼實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn