包掃描自定義注解類並實例化


 

1.  新建Maven 項目   annotation

 

2.   pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.java</groupId>
    <artifactId>annotation</artifactId>
    <version>1.0.0-SNAPSHOT</version>


    <!-- 配置版本常量 -->
    <properties>
        <jdk.version>1.7</jdk.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

 

3.   Service.java

package com.java.annotation;

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Service {

    String value();

}

 

4.   TestService.java

package com.java.service;

import com.java.annotation.Service;

@Service("test")
public class TestService {

    public void sayHello() {
        System.out.println("Hello TestService!");
    }

}

 

5.   DemoService.java

package com.java.service;

import com.java.annotation.Service;

@Service("demo")
public class DemoService {

    public String execute(String name) {
        return "DemoService: " + name;
    }

}

 

6.   BeanFactory.java

package com.java.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.reflections.Reflections;

import com.java.annotation.Service;

public class BeanFactory {

    /**
     * Bean對象容器
     */
    private static final Map<String, Object> beanContainer = new HashMap<String, Object>();

    /**
     * 初始化指定包下的所有@Service注解標記的類
     * 
     * @param packageName 初始化包路徑
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static void init(String packageName) throws InstantiationException, IllegalAccessException {
        Reflections f = new Reflections(packageName);
        Set<Class<?>> set = f.getTypesAnnotatedWith(Service.class);
        for (Class<?> c : set) {
            Object bean = c.newInstance();
            Service annotation = c.getAnnotation(Service.class);

            beanContainer.put(annotation.value(), bean);
        }
    }

    /**
     * 根據注解名獲取實例
     * 
     * @param beanName 注解的名稱
     * @return 對應實例
     */
    public static Object getBean(String beanName) {
        return beanContainer.get(beanName);
    }

    /**
     * 根據注解名獲取指定類型的實例
     * 
     * @param beanName bean名稱,注解指定的value值
     * @param beanClass bean類型
     * @return 指定類型的實例
     */
    public static <T> T getBean(String beanName, Class<T> beanClass) {
        return beanClass.cast(getBean(beanName));
    }

}

 

7.   Run.java

package com.java.run;

import com.java.factory.BeanFactory;
import com.java.service.DemoService;
import com.java.service.TestService;

public class Run {
    public static void main(String[] args) {
        try {

            // 實例化com.java.service下的所有@Service標記的類
            BeanFactory.init("com.java.service");

            TestService test = BeanFactory.getBean("test", TestService.class);
            test.sayHello();

            DemoService demo = BeanFactory.getBean("demo", DemoService.class);
            String result = demo.execute("Jack");
            System.out.println(result);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}

 

 

8.   運行第7步創建的Run的主方法,測試運行結果,如下:

Hello TestService!
DemoService: Jack

 

 

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM