包扫描自定义注解类并实例化

 

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

 

 

.

posted @ 2018-12-07 19:21  诚信天下  阅读(4939)  评论(0编辑  收藏  举报