1. 程式人生 > 其它 >spring5入門(八):基於註解管理bean,建立物件

spring5入門(八):基於註解管理bean,建立物件

  • 註解簡介
註解是程式碼特殊標記,格式:@註解名稱(屬性名稱=屬性值, 屬性名稱=屬性值..)
使用註解,註解作用在類上面,方法上面,屬性上面
使用註解目的:簡化 xml 配置
  • 有關bean的註解
@Component
@Service
@Controller
@Repository
  • 使用註解建立物件

  • 新增依賴

  • 開啟元件掃描

<?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">

    <context:component-scan base-package="com.ychen"></context:component-scan>

</beans>
  • 建立bean
@Component(value = "userService")
public class UserService {

    public void add() {
        System.out.println("service add.......");
    }

}
  • 測試方法
public class Test3 {

    @Test
    public void testAdd() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }

}
  • 控制檯
com.ychen.spring.ser.UserService@452e19ca
service add.......

Process finished with exit code 0