Two configurations xml version of the bean in four ways springAOP created automatically injected whole bean annotations automatically injected three ways Object bean object attributes injection spring dependency injection

1.Spring Dependency Injection

1.1 What is the spring

It is a lightweight container frame and IOC (DI) and the AOP

IOC: Inversion of control used to be our own new objects now create bean way, is to help us to create spring

DI: It is spring after dependency injection container frame, is a bean (loading object) container frame, spring to help me create a good object, we create good object in the corresponding class which is injected into the process

AOP: aspect-oriented programming

AOP usage scenarios:

Transaction Management

Log Management

Performance Control

1.2 spring of DI DI

1.2.1 set way of injection (beginning)

before

applicationContext.xml configuration found by fully qualified name of the class to the class object is created inside pass by set method
<bean id = "userService" class = "... UserServiceImpl">

    
  
UserController{

​	private UserService userService;
// 默认就是 通过set属性传值 
​	void setUserService(UserService userService){

​    		this.userServicer = userService;
     }
}

1.2.2 constructor injection

index index injection

 注意value 值对应类型   索引从0开始
<constructor-arg index="0" value="123"></constructor-arg>

name parameter name injected

  
<constructor-arg name="id" value="456"></constructor-arg>

type injection type

若是有多个相同的类型 依次添加值即可
 <constructor-arg type="java.lang.Long" value="111"></constructor-arg>

1.2.3 Class properties which injection

属性注入:  最常用就是基本类型和引用类型注入
 //基本数据类型注入
   <property name="id" value="111"></property>
   <property name="name" value="康康"></property>
// ref  引用一个对象    
   <property name="hellobean" ref="hb"></property>
   <property name="hellobean">
     //直接注入一个对象
          <bean class="xxxx"></bean>
    </property>

 <!-- 数组注入方式1  属性注入底层还是使用的set方法-->
<property name="strings" value="A,B,B,B"></property

                <!-- 数组注入方法二-->
<property name="strings">
<array >
<value>是尼玛 </value>
<value>是我</value>
</array>
</property>
 <!-- 集合注入方法-->
<property name="list">
<list>
    <value>你让我说点啥好</value>
    <value>你让我说点啥好</value>
    <!--创建的对象 每次都是不同的对象-->
    <bean class="_01_di.cn.itsource.HelloBean"></bean>
    <bean class="_01_di.cn.itsource.HelloBean"></bean>
    <!-- 引用的两个地址是一样的 -->
    <ref bean="hello"></ref>
    <ref bean="hello"></ref>
</list>

 <!-- 集合注入方法 set-->
<property name="set">
 <set>
 <value>小胡</value>
 <value>小胡</value>
 // 注入一个bean对象 注入的对象地址都是不同的
      <bean class="_01_di.cn.itsource.HelloBean"></bean>
     <bean class="_01_di.cn.itsource.HelloBean"></bean>
     // 引用的地址是一样的
     <ref bean="hello"></ref>
     <ref bean="hello"></ref>
 </set>


<!-- map传值-->
<property name="hp">
<map>
<entry key="小胡" value="小幸福"></entry>
<entry key="小长" value="陆小凤"></entry>
</map>

</property>


注入properties
// 不支持中文
<property name="prop1">
<value>
driverClassName=com.mysql.jdbc.Driver
username=qiang强
</value>
</property> 
<property name="prop2">
//支持中文
<props>
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
<prop key="username">qiang强</prop>
</props>
</property>

1.3 XML version of the automatic injection

Can byName - automatically injected by name
or byType injection - according to the type of automatic injector (default is bytype)
root beans default-autowire = "byName" bean all the current configuration file takes effect
the child nodes bean autowire = "byType" only for the current bean into force

Are carried out by injecting the set method or constructor Normally if we need to inject a bean to another bean, in fact, also supports Spring bean is automatically injected. When you define a bean we can specify whether you want to automatically inject current bean to its associated bean by bean autowire property element. Optional value autowire has four attributes.

  • no: defaults. It means no automatic injection.
    • byName: automatic injection by name. As a beanA setBeanB () method, specifying when autowire = "byname" Spring automatically seeks bean called "beanB" in the bean container to an automatic injection by setBeanB beanA method.
    • byType: automatic injection according to the type. As a BeanA setBeanB (BeanB b) methods, when specified autowire = "byType" Spring bean container will automatically BeanB type of the bean setBeanB () method to inject beanA. However, it will throw an exception if there are two or more types of BeanB case of bean container. If there are two methods to solve the same type of baen when you can use the name to inject
    • constructor: equivalent to byType, except when specified autowire = automatically injected through shows a construction method according to the type when "constructor".

Detailed xml


    <bean id="userController" class="_02_autoxml.cn.itsource.UserController" autowire="byType">
        <!--<property name="userService" ref="service"></property>-->
    </bean>

    <bean id="userDao" class="_02_autoxml.cn.itsource.UserDao"></bean>

    <bean id="userService" class="_02_autoxml.cn.itsource.UserServiceImpl">
       <!-- <property name="userDao" ref="dao"></property>-->
    </bean>


Notes version 1.4 XML injection

扫描包路径  扫描注解:
        @Component 普通类上面打的注解(普通仓库), @Repository, @Service,@Controller
<context:component-scan base-package="_03_annoxml.cn.itsource"></context:component-scan>

If an interface has two implementations of the case:

       方案一:一个接口有多个实现的情况下面 通过名字去区分
       方案二:通过Resource这个注解
       区别:@Autowired@Qualifier 都是属于spring的注解 ,
          Resource使用jdk的注解 推荐使用Autowired和Qualifier,可以和spring进行无缝衔接
          autowired默认是根据类型匹配,如果类型匹配不上在根据名字匹配
          而Resource默认根据名字匹配,名字匹配不上就匹配类型

2 Spring AOP features inside

2.1 What is springAOP

aop: Oriented Programming section of
The AOP out not to replace OOP (Object Oriented Programming), it is just over the role as a complement to solve some of our resolve OOP (Object Oriented) can not (or very difficult to solve) some code.
AOP use exists only in certain situations (with a cross-cutting logic applications), the cross-section of the logical explanation may be more abstract, we put a little more specific, AOP can be used for transaction management, log management, performance monitoring and other places .

2.2aop implementation

Proxy mode is implemented underlying aop

jdk proxy mode - with an interface case

cglib dynamic proxy - no interface case

2.3 springaop configuration

xml version of the configuration

// 扫描主键
<context:component-scan base-package="_04_aopxml"></context:component-scan>
    <aop:config>
       // 在哪里切入
        <aop:pointcut id="pointcut" expression="execution(* _04_aopxml.I*Service.*(..))"></aop:pointcut>
        <!--配置通知  引用事务管理--> 
        <aop:aspect ref="txManager">
            <!-- 前置通知-->
            <!--<aop:before method="begin" pointcut-ref="pointcut"></aop:before>
            &lt;!&ndash; 后置通知&ndash;&gt;
            <aop:after-returning method="commit" pointcut-ref="pointcut"></aop:after-returning>
            &lt;!&ndash; 最终通知&ndash;&gt;
            <aop:after method="close" pointcut-ref="pointcut"></aop:after>
            &lt;!&ndash; 异常通知&ndash;&gt;
            <aop:after-throwing method="rollback" throwing="e" pointcut-ref="pointcut"></aop:after-throwing>-->
            <!-- 环绕通知-->
            <aop:around method="around" pointcut-ref="pointcut"></aop:around>
        </aop:aspect>
    </aop:config>
    <bean id="txManager" class="_04_aopxml.TxManager"></bean>

An annotated version of the configuration

@Component
@Aspect
public class TxManager {

   // 在哪里切入 执行
    @Pointcut("execution(* _05_aopanno.I*Service.*(..))")
    //切入点
    public void pointcut(){}

    //<aop:before method="begin" pointcut-ref="pointcut"></aop:before>
    //@Before("pointcut()")
    public void begin(){
        System.out.println("开启事务");
    }

  ///  @After("pointcut()")
    public void commit(){
        System.out.println("提交事务");
    }
    //@AfterReturning("pointcut()")
    public void close(){
        System.out.println("关闭");
    }
    //所有的异常的父类
   // @AfterThrowing(value = "pointcut()",throwing = "e")
    public void rollback(Throwable e){
        System.out.println("回滚事务"+e.getMessage());
    }

    //环绕通知
    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint){
        try {
            begin();
            //调用方法
            joinPoint.proceed();
            commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally{
            close();
        }
    }
}

3 Bean to create a way

Previous model: create new objects by way of

spring fashion: spring to help us create the bean. - Create a bean way

3.1 Bean created a way

To create the bean by the constructor with no arguments - the most common way

Configuration

<bean id="mybean" class="_06_bean.Mybean"></bean>

Second way to create 3.2 Bean

FactoryBean factory object

 //实现 FactoryBean
public class MybeanFactoryBean implements FactoryBean<Mybean> {
    //返回对象
    public Mybean getObject() throws Exception {
        return new Mybean("xxx", "18");
    }
   
    public Class<?> getObjectType() {
        return Mybean.class;
    }
    //是否单例
    public boolean isSingleton() {
        return true;
    }
}

Three ways to create 3.3 Bean

To obtain the bean class which defines static methods

public class MybeanFactory {

    public static Mybean getBean(){
        return new Mybean();
    }
}
<bean class="_06_bean.MybeanFactory" factory-method="getBean"></bean>

Four ways to create 3.4 Bean

public class MybeanFactory1 {
    //普通方式
    public  Mybean getBean1(){
        return new Mybean();
    }
}
<bean class="_06_bean.MybeanFactory1" id="mybeanFactory1"></bean>
    <bean factory-bean="mybeanFactory1" factory-method="getBean1"></bean>
public class MybeanFactory1 {
    //普通方式
    public  Mybean getBean1(){
        return new Mybean();
    }
}
<bean class="_06_bean.MybeanFactory1" id="mybeanFactory1"></bean>
    <bean factory-bean="mybeanFactory1" factory-method="getBean1"></bean>
Published 23 original articles · won praise 2 · Views 937

Guess you like

Origin blog.csdn.net/metjoyful/article/details/101293400