天天看點

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)

Spring的bean管理(注解建立對象)

    AOP

    (1)aop概述

  (2)aop底層原理

  (3)aop操作相關術語     

Spring的bean管理(注解)

注解介紹

   1.代碼裡面特殊标記,使用注解可以完成功能。

   2.注解寫法@注解名稱(屬性名稱=屬性值)

   3.注解使用在類上面,方法上面和屬性上面。

Spring的bean管理注解準備

1 導入jar包

  (1)導入基本的jar包

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)

    (2) 建立類,建立方法

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)

     User.java 加注解

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)
package com.cn.anno;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component(value="user")  //<bean id="user" class="">
@Scope(value="prototype") //建立多執行個體
public class User {
	public void add(){
		System.out.println("add...........");
	}
}
           

除了  compoment屬性外,還有

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)

 2 建立對象有四個注釋  

   (1)@Component   :web層

     (2) @Controller  :業務層

     (3) @Service     :持久層

     (4) @Repository

   目前這四個注釋功能是一樣的,都建立對象。

  3 建立對象單執行個體還是多執行個體

@Scope(value="prototype") //建立多執行個體
           

單執行個體  就是  Singleton

TestAnno.java

package com.cn.anno;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAnno {
	@Test
	public void testUser(){
		ApplicationContext context=
				new ClassPathXmlApplicationContext("bean1.xml");
		User user=(User) context.getBean("user");
		System.out.println(user);
		user.add();
	}
}
           

(3)建立spring配置檔案,引入限制

       (1)第一天做ioc基本功能,引入限制beans

         (2) 做spring的ioc注解開發,引入新的限制      bean1.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"
    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 -->
<!-- 開啟注解掃描 (1) 到包裡面掃描類 方法 屬性上面是否有注解 -->
	<context:component-scan base-package="com.cn.anno"></context:component-scan>

</beans>
           

測試結果

Spring的bean管理(注解建立對象)Spring的bean管理(注解建立對象)