spring中定義一個Bean以及生成一個Bean實例,具體


Bean配置有三種方法:

  • 基於xml配置Bean
  • 使用注解定義Bean
  • 基於java類提供Bean定義信息

一個Bean的類結構:

    /* Bean Id */  
    private String id;   
    /* Bean Class */  
    private String type;   
    /* Bean Property */  屬性
    private Map<String, Object> properties = new HashMap<String, Object>(); 

Spring 就開始加載我們的配置文件了,將我們配置的信息保存在一個HashMap中,HashMap的key就是Bean 的 Id ,HasMap 的value是這個Bean,包括會掃描屬性並保存到properties中。

1.基於xml文件定義:

使用:

//主類
public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext(
                "applicationContext.xml");
        Animal animal = (Animal) context.getBean("animal");
        animal.say();
}
//Cat類
public class Cat implements Animal {
    private String name;
    public void say() {
        System.out.println("I am " + name + "!");
    }
    public void setName(String name) {
        this.name = name;
    }
}

application.xml配置文件:

<bean id="animal" class="phz.springframework.test.Cat">
        <property name="name" value="kitty" />
</bean>

通過反射創建類對象

public static Object newInstance(String className) {   
        Class<?> cls = null;   
        Object obj = null;   
        try {   
            cls = Class.forName(className);   
            obj = cls.newInstance();   
        } catch (ClassNotFoundException e) {   
            throw new RuntimeException(e);   
        } catch (InstantiationException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalAccessException e) {   
            throw new RuntimeException(e);   
        }   
        return obj;   
}

通過下面這個方法獲取每個屬性的setter方法來進行注入

public static void setProperty(Object obj, String name, String value) {   
        Class<? extends Object> clazz = obj.getClass();   
        try {   
            String methodName = returnSetMthodName(name);//獲取這個屬性的setter方法   
            Method[] ms = clazz.getMethods();   
            for (Method m : ms) {   
                if (m.getName().equals(methodName)) {   
                    if (m.getParameterTypes().length == 1) {   
                        Class<?> clazzParameterType = m.getParameterTypes()[0];   
                        setFieldValue(clazzParameterType.getName(), value, m,   
                                obj);   
                        break;   
                    }   
                }   
            }   
        } catch (SecurityException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalArgumentException e) {   
            throw new RuntimeException(e);   
        } catch (IllegalAccessException e) {   
            throw new RuntimeException(e);   
        } catch (InvocationTargetException e) {   
            throw new RuntimeException(e);   
        }   
}

2.通過@Component@Configuration注解來定義

@Component

@Component("userDao")
public class UserDao {}

除了@Component以外,Spring提供了3個功能基本和@Component等效的注解,它們分別用於對DAO、Service及Web層的Controller進行注解,所以也稱這些注解為Bean的衍型注解:(類似於xml文件中定義Bean<bean id=" " class=" "/>

  • @Repository:用於對DAO實現類進行標注;
  • @Service:用於對Service實現類進行標注;
  • @Controller:用於對Controller實現類進行標注;

之所以要在@Component之外提供這三個特殊的注解,是為了讓注解類本身的用途清晰化。

@Configuration

普通的POJO類中只要標注@Configuration注解,就可以為spring容器提供Bean定義的信息了,每個標注了@Bean的類方法都相當於提供了一個Bean的定義信息。

//①將一個POJO標注為定義Bean的配置類
@Configuration
public class AppConf {
    //②以下兩個方法定義了兩個Bean,以提供了Bean的實例化邏輯
    @Bean
    public UserDao userDao(){
       return new UserDao();    
    }
    
    @Bean
    public LogDao logDao(){
        return new LogDao();
    }
    //③定義了logonService的Bean
    @Bean
    public LogonService logonService(){
        LogonService logonService = new LogonService();
                //④將②和③處定義的Bean注入到LogonService Bean中
        logonService.setLogDao(logDao());
        logonService.setUserDao(userDao());
        return logonService;
    }
}

參考:

https://www.cnblogs.com/wuchanming/p/5426746.html

 


免責聲明!

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



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