bean别名配置

bean别名配置

// AppForName.java
public class AppForName {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        // 通过别名获取bean
        BookService bookService = (BookService) ctx.getBean("service");
        bookService.save();
    }
}
<!--applicationContext.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="bookDao" name="dao" class="com.charley.dao.impl.BookDaoImpl"/>

    <!--name给bean取别名,多个别名用空格隔开-->
    <bean id="bookService" name="service service2 booEbi" class="com.charley.service.impl.BookServiceImpl">
        <property name="bookDao" ref="bookDao"/>
    </bean>
</beans>

注意:获取bean无论是通过id还是name获取,如果无法找到,将会抛出NoSuchBeanDefinitionException