Spring复习:(59)标记性注解和qualifier配合使用

一、定义接口

package cn.edu.tju.domain;

public interface MovieCatalog {
}

二、定义步骤一中接口的实现类

package cn.edu.tju.domain;

public class SimpleMovieCatalog implements MovieCatalog{
}

三、定义标记性注解

package cn.edu.tju.anno;

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Offline {

}

四、定义bean,注入步骤一中的接口,并使用标记性注解

package cn.edu.tju.anno;

import cn.edu.tju.domain.MovieCatalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MovieRecommender {
    @Autowired
    @Offline
    public MovieCatalog offlineCatalog;

}


五、配置文件beans18.xml



    
        
    

    


六、主类

package cn.edu.tju;

import cn.edu.tju.anno.MovieRecommender;
import cn.edu.tju.study.service.anno.domain.MyValueCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Start18 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("beans18.xml");
        MovieRecommender movieRecommender = applicationContext.getBean("movieRecommender", MovieRecommender.class);
        System.out.println(movieRecommender.offlineCatalog);

    }
}

你可能感兴趣的:(Spring,spring,java,后端)