您的位置:首页 > 编程语言 > Java开发

Spring的bean管理(注解创建对象)

2017-11-08 18:29 489 查看

Spring的bean管理(注解)

注解介绍

1 代码里面特殊标记,使用注解可以完成功能

2 注解写法 @注解名称(属性名称=属性值)

3 注解使用在类上面,方法上面 和 属性上面

 

Spring注解开发准备

1 导入jar包

(1)导入基本的jar包



(2)导入aop的jar包



 

2 创建类,创建方法

3 创建spring配置文件,引入约束

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

(2)做spring的ioc注解开发,引入新的约束



具体位置在:spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html 下的 xsd-configuration.html(用浏览器打开)中,把鼠标滑到最后,往前找,找到  40.2.8 the context schema ,即是。

创建对象

1、具体代码如下

(1)bean1.xml (放在 src 下,名称不重要)

<?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.liuyanzhao.anno"></context:component-scan>
</beans>

注意:这个地方的 base-package ,如果是多个包,可以以逗号分隔,或者以最大的包替代(如com.liuyanzhao 或 com)

(2)User.java

package com.liuyanzhao.anno;

import org.springframework.stereotype.Component;

@Component(value = "userId")  //<baan id="user" class="" >
public class User {
    public void add() {
        System.out.println("add..........");
    }
}

注意:

这个地方的的注解 @Component(value = "userId) 相当于之前学的 bean管理(xml方式)中的 <bean id="user" class="com.liuyanzhao.User">
这里的 Component 注解,可以以其他三种注解替换。



(3)测试类 TestAnno.java

package com.liuyanzhao.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("userId");
        System.out.println(user);
        user.add();
    }
}

注意:这里还要添加一个 JUnit 包,用来测试方法

 

参考:传智播客视频

本文链接:https://liuyanzhao.com/5629.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: