zoukankan      html  css  js  c++  java
  • Spring框架bean的注解管理方法之一 使用注解生成对象

    首先在原有的jar包:

    需Spring压缩包中的四个核心JAR包

    beans 、context、core 和expression

    下载地址:

    https://pan.baidu.com/s/1qXLHzAW

    以及日志jar包

    commons-logging 和log4j

    下载地址:

    https://pan.baidu.com/s/1mimTW5i

    再增加一个

    spring-aop-5.0.1.RELEASE.jar

    增加注解功能的jar包名字是aop有些奇怪(不是annotation ,也不是context)


    然后,src中建立一个xml配置文件,增加新的context的约束语句,如下:

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

    注解的方法xml中配置对象及属性只用这一句

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

    即可,com.swift是包名,最好写上一级,可以扫描到里边所有的包

    下边使用注解来创建对象:

    package com.swift.user;
    
    import org.springframework.stereotype.Component;
    
    @Component(value="user")
    public class User {
        public String fun() {
            return "The User's fun()..........";
        }
    }
     

    注解创建对象

    @Component(value="user")

    或者

    @Component

    默认就是生成user对象

    相当于之前在xml配置文件中使用<bean id="user" class="com.swift.User"></bean>

    实际上除了可以用@Component 还可以用@Service @Controller @Repository ,功效一样,分别预备service层 web层 dao层使用的

    默认单例,如果要多例可以这样写

    @Component(value="user")

    @Scope(value="prototype")

    关于value="prototype" 还有待补充


     struts2的Action使用多例 有成员变量的用多例 否则会引起多线程的并发



  • 相关阅读:
    在Flask/Django中增加下载Excel的功能
    如何设置原创声明
    python3中用django下载文件,中文名乱码怎么办?
    关于状态机工作流的编程方法
    用python解析word文件(三):style
    用python解析word文件(二):table
    用python解析word文件(一):paragraph
    python中的轻量级定时任务调度库:schedule
    在windows下的虚拟环境中使用tk,要留神了
    压平列表
  • 原文地址:https://www.cnblogs.com/qingyundian/p/7846098.html
Copyright © 2011-2022 走看看