Spring Bean管理--註解方式——(五)

文章目錄


Spring2.5引入使用註解定義Bean

@Component 描述Spring框架中的Bean

@Repository用於對DAO實現類進行標註

@Service用於對Service實現類進行標註

@Controller用於對Controller實現類進行標註

找文檔:
spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html
找到下面的,40.2.8the context schema

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
  <!--開啓註解掃描-->
  <context:component-scan base-packge="xx包名"/>
</beans>

新建UserService類

/**
 * Spring的Bean管理的註解方式:
 *  * 傳統方式需要去XML中配置<bean id="" class=""></bean>
 */
 @Component("userService")
 public class UserService {
    public String sayHello(String name){
        return "Hello" + name;
    }
}

新建測試類

@Test
    public void demo1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = (UserService) applicationContext.getBean("userService");

        String s = userService.sayHello("張三");

        System.out.println(s);
    }

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章