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

avatar 2017年08月05日11:23:00 1 2809 views
博主分享免费Java教学视频,B站账号:Java刘哥

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 下,名称不重要)
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  7.     <!--开启注解扫描-->
  8.     <context:component-scan base-package="com.liuyanzhao.anno"></context:component-scan>
  9. </beans>
注意:这个地方的 base-package ,如果是多个包,可以以逗号分隔,或者以最大的包替代(如com.liuyanzhao 或 com) (2)User.java
  1. package com.liuyanzhao.anno;
  2. import org.springframework.stereotype.Component;
  3. @Component(value = "userId")  //<baan id="user" class="" >
  4. public class User {
  5.     public void add() {
  6.         System.out.println("add..........");
  7.     }
  8. }
注意:
  • 这个地方的的注解 @Component(value = "userId) 相当于之前学的 bean管理(xml方式)中的 <bean id="user" class="com.liuyanzhao.User">
  • 这里的 Component 注解,可以以其他三种注解替换。
(3)测试类 TestAnno.java
  1. package com.liuyanzhao.anno;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. public class TestAnno {
  6.     @Test
  7.     public void testUser() {
  8.         ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
  9.         User user = (User) context.getBean("userId");
  10.         System.out.println(user);
  11.         user.add();
  12.     }
  13. }
注意:这里还要添加一个 JUnit 包,用来测试方法   参考:传智播客视频 本文链接:https://liuyanzhao.com/5629.html
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0