spring框架 多种注入方法+注释实现IOC AOP

一,多种方式实现依赖注入
1.构造注入
构造注入是一种高内聚的体现,特别是针对有些属性需要在对象在创建时候赋值,且后续不允许修改(不提供setter方法)

<bean id="demo3" class="com.bdqn.cn.Demo">
        <constructor-arg><value type="java.lang.String">哈辛</value></constructor-arg>
        <constructor-arg><value type="int">3</value></constructor-arg>
    </bean>

2.设值注入:通过setter访问器注入数据。
设值注入的优劣势:设值注入使用灵活,但时效性不足,并且大量的setter访问器增加了类的复杂性。

 <bean id="author" class="com.bdqn.cn.Author">
        <property name="name" value="夏洛特"/>
        <property name="age" value="31"/>
        <property name="sex" value="女"/>
    </bean>


    <bean id="book" class="com.bdqn.cn.Book">
        <property name="name" value="简爱"/>
        <property name="author" ref="author"/>
    </bean>

3.p名称空间的使用

spring2.5以后,为了简化setter方法属性注入,引用p名称空间的概念,可以将 子元素,简化为元素属性配置 !!
使用p命名空间必须导入 xmlns:p=“http://www.springframework.org/schema/p

<bean id="user" class="entity.User" p:id="1" p:password="123" p:username="zhangsan"/>

二,处理不同类型的数据:特殊字符串处理
JavaBean
List
Array
Set
Map
Properties
空字符串
null值

实体类 :TestEntity

package com.bdqn.cn;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class TestEntity {
    private String specialCharacter1; // 特殊字符值1
    private String specialCharacter2; // 特殊字符值2
    private User innerBean; // JavaBean类型
    private List<String> list; // List类型
    private String[] array; // 数组类型
    private Set<String> set; // Set类型
    private Map<String, String> map; // Map类型
    private Properties props; // Properties类型
    private String emptyValue; // 注入空字符串值
    private String nullValue = "init value"; // 注入null值

    public void setSpecialCharacter1(String specialCharacter1) {
        this.specialCharacter1 = specialCharacter1;
    }

    public void setSpecialCharacter2(String specialCharacter2) {
        this.specialCharacter2 = specialCharacter2;
    }

    public void setInnerBean(User user) {
        this.innerBean = user;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setArray(String[] array) {
        this.array = array;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    public void setEmptyValue(String emptyValue) {
        this.emptyValue = emptyValue;
    }

    public void setNullValue(String nullValue) {
        this.nullValue = nullValue;
    }

    public void showValue() {
        System.out.println("特殊字符1:" + this.specialCharacter1);
        System.out.println("特殊字符2:" + this.specialCharacter2);
        System.out.println("内部Bean:" + this.innerBean.getUsername());
        System.out.println("List属性:" + this.list);
        System.out.println("数组属性[0]:" + this.array[0]);
        System.out.println("Set属性:" + this.set);
        System.out.println("Map属性:" + this.map);
        System.out.println("Properties属性:" + this.props);
        System.out.println("注入空字符串:[" + this.emptyValue + "]");
        System.out.println("注入null值:" + this.nullValue);
    }
}

spring配置文件:spring_config.xml

<bean id="entity" class="com.bdqn.cn.TestEntity">
        <!--使用<![CDATA[]]>标记处理XML特殊字符-->
        <property name="specialCharacter1">
            <value><![CDATA[P&G]]]></value>
        </property>
        <!--把XML特殊字符替换为实体引用-->
        <property name="specialCharacter2">
            <value>P&amp;G</value>
        </property>

        <!--定义内部Bean-->
        <property name="innerBean">
            <bean class="com.bdqn.cn.User">
                <property name="username">
                    <value>Mr.Inner</value>
                </property>
            </bean>

        </property>
        <!--List类型-->
        <property name="list">
            <list>
                <!--定义List中的元素-->
                <value>足球</value>
                <value>篮球</value>
            </list>
        </property>

        <!--注入数组类型-->
        <property name="array">
            <list>
                <value>足球</value>
                <value>篮球 </value>
            </list>
        </property>

        <!--Set类型-->
        <property name="set">
            <set>
                <value>足球</value>
                <value>篮球 </value>
            </set>
        </property>

        <!--Map类型-->
        <property name="map">
            <map>
                <!--定义Map中的键值对-->
                <entry>
                    <key>
                        <value>football</value>
                    </key>
                    <value>足球</value>
                </entry>
                <entry>
                    <key>
                        <value>basketball</value>
                    </key>
                    <value>篮球</value>
                </entry>
            </map>
        </property>
        <!--注入Properties类型-->
        <property name="props">
            <props>
                <!--定义Properties中的键值对-->
                <prop key="football">足球</prop>
                <prop key="basketball">篮球</prop>
            </props>
        </property>
        <!--注入空字符串值-->
        <property name="emptyValue">
            <value></value>
        </property>
        <!--注入null值-->
        <property name="nullValue">
            <null/>
        </property>
    </bean>

测试类

  @Test
    public void testEntity(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");
        TestEntity testEntity = (TestEntity)context.getBean("entity");
        System.out.println(testEntity.toString());
    }
}

三 ,使用注解实现IoC的配置
之前我们配置IOC(控制反转)都是在xml中配置,现在通过注解配置IOC会减少很多代码

使用注解实现Bean组件的定义:

(1)@Component:该注解与等效。

(2)@Respository:该注解用于标注Dao类。

(3)@Service:该注解用于标注业务逻辑类。

(4)@Controller:该注解用于标注控制器类。

使用注解实现Bean组件的装配:

(1)@Autowired:该注解用于注入所依赖的对象。

(2)@Autowired 采用按类型匹配的方式为属性自动装配合适的依赖对象,即容器会查找和属性类型相匹配的Bean组件,并自动为属性注入。

(3)@Qualifier:该注解用于指定所需Bean的名字。

加载注解定义的Bean:

首先在spring配置文件中添加对context命名空间的声明,然后使用context命名空间下的component-scan标签扫描注解标注的类,base-package 属性指定了需要扫描的基准包。

实现IOC注解
配置 spring_zhujie.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:aop="http://www.springframework.org/schema/aop"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <!--多个包逗号隔开-->
    <context:component-scan base-package="com.bdqn.dao,com.bdqn.service"/>
</beans>

数据访问层:userDaoImpl.java

package com.bdqn.dao;

public interface UserDao {
    //通过用户名得到密码
    public String getPwd(String name);
}

业务逻辑层:userServiceImpl.java

package com.bdqn.dao.daoimpl;

import com.bdqn.dao.UserDao;
import org.springframework.stereotype.Repository:

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public String getPwd(String name) {
        //忽略数据库操作
        return "admin";
    }
}

业务逻辑层:userServiceImpl.java

package com.bdqn.service.serviceimpl;

import com.bdqn.dao.UserDao;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements UserService {
   // @Autowired
    	//@Qualifier("userDao")
    	private UserDao userDao;
    	@Override
    	public String getPwd(String name) {
       		 return userDao.getPwd(name);
    }
}

测试类

  @Test
    public void testzhujie(){
        ApplicationContext context=new ClassPathXmlApplicationContext("spring_zhujie.xml");
         UserService userService= (UserService) context.getBean("userService");
         String pwd= userService.getPwd("admin");
        System.out.println(pwd);
    }

四 、使用注解定义切面

使用注解实现一个简单的AOP切面:

spring配置文件:springConfig.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
     <aop:aspectj-autoproxy/>
    <bean id="target" class="com.bdqn.aop.Target"></bean>
    <bean id="adviceTarget" class="com.bdqn.aop.AdviceTarget"></bean>

</beans>

目标类 Taget .Java

package com.bdqn.aop;

import org.springframework.stereotype.Component;

//目标类

@Component("target")
public class Target {
    public String show(String name) {
        System.out.println("这是目标方法。。。。");
        return "hello"+name;
    }
}


目标增强类AdviceTaget.java

package com.bdqn.aop;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

/**
 * Created by 18054 on 2018/9/25.
 */
//增强类
    @Aspect
public class AdviceTarget {

    @Before("execution(* com.bdqn.aop.*.*(..))")
    public void before(JoinPoint jp){
        System.out.println("参数3"+jp.getArgs()+",方法名"+jp.getSignature()+",目标对象:"+jp.getTarget());
    }
    @After("execution(* com.bdqn.aop.*.*(..))")
    public void after(JoinPoint jp){
        System.out.println("这是后置增强");
    }
    @AfterReturning(value = "execution(* com.bdqn.aop.*.*(..))",returning = "value")
    public void afterReturn(JoinPoint jp,String value ){
        System.out.println("后置带返回值"+value);
    }
    @AfterThrowing(value = "execution(* com.bdqn.aop.*.*(..))", throwing = "ex")
    public void afterException(JoinPoint jp,Exception ex){
        System.out.println("后置带异常"+ex);
    }
    @Around("execution(* com.bdqn.aop.*.*(..))")
    public void around(ProceedingJoinPoint jp){
        String str= (String) jp.getArgs()[0];
        if(str.equals("admin")){
            //有权限,可以访问目标方法
            try {
                String value=  jp.proceed().toString();
                System.out.println("返回值"+value);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }else {
            //无权限
            System.out.println("没有权限");
            //跳转到登陆页面
        }
    }

}

测试类

  @Test
    public void testTarget() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring_aop.xml");
        Target target = (Target) context.getBean("target");
        System.out.println(target);
    }```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值