spring通过ApplicationContext对象获取类

直接上代码

applicationContext.xml



    
    
    

工厂:

package com.didispace.Duty;

import org.springframework.context.ApplicationContext;

/**
 * @author stone
 */
public class MethodHandlerFactory {

    public static SayHandler reflectHandle(ApplicationContext applicationContext, String method) {
        String beanName = method + "Duty";
        try {
            SayHandler handler = applicationContext.getBean(beanName, SayHandler.class);
            return handler;
        } catch (Exception e) {
            return null;
        }
    }

}
interface
package com.didispace.Duty;

/**
 * @author stone
 */
public interface SayHandler {

    void say();

}
package com.didispace.Duty;

import org.springframework.stereotype.Component;

/**
 * @author stone
 */
@Component("TomDuty")
public class TomSayHandler implements SayHandler {
    @Override
    public void say() {
        System.out.println("TomSayHandler say !");
    }
}
package com.didispace.Duty;

import org.springframework.stereotype.Component;

/**
 * @author stone
 */
@Component("TtDuty")
public class TtSayHandler implements SayHandler {
    @Override
    public void say() {
        System.out.println("TtSayHandler say !");
    }
}

测试类:

package com.didispace.Duty;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author stone
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class Test {
    @Autowired
    private ApplicationContext applicationContext;

    @org.junit.Test
    public void main1() {
        SayHandler sayHandler = MethodHandlerFactory.reflectHandle(applicationContext, "Tom");
        sayHandler.say();
    }

}

运行结果:TomSayHandler say !

你可能感兴趣的:(spring)