Spring AOP IOC affairs

Spring IOC and AOP is the core of the two points IOC: Inversion of Control AOP: Aspect Oriented Programming

IOC is that we define the class registration to Sping container so that we no longer need to manually fetch new one instance but by the Spring container. Spring container will be based on the profile (profile may be used directly without having to write annotations configuration) to create objects caller, while the called object instantiated object () method of the form set by the constructor or injected to the caller the object among.

Through the IOC container, developers do not need to focus on how objects are created, and a new class is also very easy to use, only need to modify the configuration file.

AOP Oriented Programming example, a developer may not be changes in the original model of the business logic can be dynamically increased log, security or exception handling.
Just do not change the original source code to add some new features before and after a certain point (cut) is Aspect Oriented Programming with Spring also supports this feature AOP First we need to import the relevant configuration in the configuration file There are three ways we achieve AOP

A first write an implementation class that implements the appropriate interface

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("已经执行了" + method.getName() + " 方法,结果为 " + o);
    }
}

public class BeforeLog implements MethodBeforeAdvice {

    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("在" + o.getClass().getName() + "执行了" + method.getName() + "方法");
    }
}

MethodBeforeAdvice interface represents an entry point function is executed before he has a name and a method name can get some kind of parameters and so on. AfterReturningAdvice interface represents an entry point function is performed after him one more argument than MethodBeforeAdvice value represents the return (because he is the starting point of the method performed only after the entry point may have a return value it can get).

The second method: a class and then write any of his transformation in the configuration file so that he may be performed before or after the entry point

public class DiyPointCut {
    public void before(){
        System.out.println("+++++++++++before+++++++++++++++");
    }

    public void after(){
        System.out.println("+++++++++++after+++++++++++++++");
    }
}

The second method and the first method is more convenient because he did not realize that the two interfaces but through the transformation of the profile compared to is what he did not realize that the two interfaces all of his function is very limited , he can not be like the first method can be obtained as a number corresponding to the entry point information

A third method is annotated by the configuration and function similar to the second approach described herein do not much.

Configuration files are as follows:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="afterlog" class="com.Jee.log.AfterLog"/>
    <bean id="beforelog" class="com.Jee.log.BeforeLog"/>
    <bean id="userserviceimpl" class="com.Jee.service.UserServiceImpl"/>

<!--    <aop:config>-->
<!--        &lt;!&ndash;第一种方式 : 切入点&ndash;&gt;-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.Jee.service.UserServiceImpl.*(..))"/>-->
<!--        &lt;!&ndash;执行环绕增加&ndash;&gt;-->
<!--        <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>-->
<!--        <aop:advisor advice-ref="beforelog" pointcut-ref="pointcut"/>-->
<!--    </aop:config>-->

    <bean id="diy" class="com.Jee.diy.DiyPointCut"/>
    <aop:config>
        <!--第二种方式 : 定义切面-->
        <aop:aspect ref="diy">
        <!--定义切入点-->
            <aop:pointcut id="point" expression="execution(* com.Jee.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

aop: config tag is not less aop need to define the dependent correlation aop: pointcut refers to the entry point of its expression is the expression of this particular entry point position () is represented by a fixed execution of this wording
execution (* com .Jee.service.UserServiceImpl. (...)) in an arbitrary meaning of this expression pointcuts any method UserServiceImpl position under the category com.Jee.service package.

IOC inversion of control

If not applicable, then comment directly in the configuration file to define classes

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
	bean标签用来实例化一个类  id表示这个实例的名字 class表示他的全类名
	property标签中的name代表类中的属性名 value表示值 
	但是 这样的话 value只能表示一些基本数据类型  那些复杂的例如 数组 集合 map等数据类型无法表示 
	这个时候我们就需要使用其他的一些标签了
    <bean id="address" class="com.Jee.entity.Address">
        <property name="city" value="武汉"/>
        <property name="stress" value="人民医院"/>
    </bean>
    
    <bean id="student" class="com.Jee.entity.Student">
        <property name="id" value="1"/>
        <property name="name">
            <null/>
        </property>
        //ref表示一个引用 如果你定义好了一个属性 你直接可以使用ref来引用你定义好的id
        <property name="address" ref="address"/>
        <property name="books">
        //如果类型是数组  就使用array标签表示 用value设置数组中的值
            <array>
                <value>"算法导论"</value>
                <value>"Java核心"</value>
                <value>"计算机组成原理"</value>
                <value>"数据库基础"</value>
            </array>
        </property>
        <property name="cards">
        //如果是map类型的话 使用map标签  用过entry表示数据 entry中有key和value
            <map>
                <entry key="校园卡" value="这是一张校园卡"/>
                <entry key="门禁卡" value="这是一张门禁卡"/>
                <entry key="水卡" value="这是一张水卡"/>
            </map>
        </property>
        <property name="games">
        //如果数据类型是set类型  使用set标签 用value标签表示set中的值
            <set>
                <value>LOL</value>
                <value>BOB</value>
                <value>FOF</value>
            </set>
        </property>
        <property name="hobbys">
        //如果数据类型是集合 就使用list标签  value标签表示list中的值
            <list>
                <value>唱</value>
                <value>跳</value>
                <value>Rap</value>
                <value>篮球</value>
            </list>
        </property>
        <property name="info">
        //类型是prop的话 使用这种(虽然我也不知道prop是什么类型)
            <props>
                <prop key="driver">driver</prop>
                <prop key="url">url</prop>
                <prop key="username">username</prop>
                <prop key="password">password</prop>
            </props>
        </property>
    </bean>

</beans>

Use annotations do not need to define the class attribute in the configuration file in the opened file annotation scan directly before the specified line package to scan all annotations in the spring will automatically scanning corresponding packet

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解-->
    <context:annotation-config/>
    <!--扫描这个包下的所有注解-->
    <context:component-scan base-package="com.Jee.entity"/>

<!--    <bean id="dog111" class="com.Jee.entity.Dog">-->
<!--        <property name="name" value="狮子汪"/>-->
<!--    </bean>-->

<!--    <bean id="cat222" class="com.Jee.entity.Cat">-->
<!--        <property name="name" value="喵尔摩斯"/>-->
<!--    </bean>-->

<!--    <bean id="person" class="com.Jee.entity.Person">-->
<!--        <property name="name" value="天人"/>-->
<!--    </bean>-->

</beans>


对应的类

//@Component注解代表这个类是一个组件 可以被@Autowired自动导入 
@Component
public class Dog {
	//@Value注解定义在字段上 表示这个字段的值
    @Value("狮子汪")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                '}';
    }

    public void speak(){
        System.out.println("wow wow wow ");
    }
}


@Component
public class Person {
    private String name;
    //@AutoWired注解 表示自动导入 像这个例子  Cat类和Dog类 如果我们已经把他们添加到了Spring容器中 我们就可以使用@AutoWired实现自动导入 而不需要手动配置
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", cat=" + cat +
                ", dog=" + dog +
                '}';
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

Use a configuration class to generate our class definition so we do not need to go use the configuration files only need to define a configuration class on the line

User类
@Component
public class User {

    @Value("1")
    private int id;
    @Value("魔法猫咪")
    private String name;
    private String[] games;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String[] getGames() {
        return games;
    }

    public void setGames(String[] games) {
        this.games = games;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", games=" + Arrays.toString(games) +
                '}';
    }
}

以上两种都是使用配置文件来注册相应的类的  要拿到我们定义好的类 需要使用如下的方法

public class MyTest {
	//这个一个junit测试类
    @Test
    public void test(){
    	//使用new ClassPathXmlApplicationContext这个类  参数是我们配置文件的名称
    	//可以使用getBean来获得我们注册的类的实例  参数是我们bean标签中的id
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Person person = (Person) context.getBean("person");
        System.out.println(person);
        System.out.println(person.getCat());
        person.getCat().speak();
        System.out.println(person.getDog());
        person.getDog().speak();
    }
}



配置类(不需要使用配置文件了 直接定义这个类就行)

//@Configuration注解表示这个类是一个配置类
@Configuration
//@Import注解可以导入其他的配置类
@Import(JeeConfig2.class)
public class JeeConfig {

	//@Bean注解表示这个方法是一个可以返回一个实例的方法 从而可以在ApplicationContext类中使用
    @Bean
    public User getUser(){
        return new User();
    }

    @Bean
    public Address address(){
        return new Address();
    }
}

使用配置类,我们获得实例的方法同上述两种有一点细微的区别

public class MyTest {
    @Test
    public void test(){
    	//new的是AnnotationConfigApplicationContext这个类  参数变成了我们定义的配置类
        ApplicationContext context = new AnnotationConfigApplicationContext(JeeConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser);
        System.out.println("1111111111111");
        System.out.println((Address)context.getBean("address"));
    }
}

Affairs in our business is very important not to be careless about the operation of the database must use a transaction to ensure its security
affairs four characteristics of the ACID
1, atomicity (Atomicity)
atomicity refers to all operations in the transaction included either all succeed, or all fail rolled back, the operator of the transaction if successful, it must be fully applied to the database if the operation fails it can not have any impact on the database.

2. Consistency (Consistency)
Consistency means that the transaction must transform the database from one consistent state to another consistent state, that is to say before and after a transaction execution and implementation must be in a consistent state. For example, if both user A and user B money add up to a total of 1000, then no matter how transfers between A and B, turn several accounts, after the end of the transaction the money add up to two users should have to be 1000, this is the transactional consistency.

3, isolation (Isolation)
isolation when a plurality of users concurrent access to the database, such as when operating simultaneously with a table, a database for each user transaction open, operation not being disturbed by other transactions, the plurality of concurrent transactions to isolate the room from each other. About the transaction isolation provides a variety of database isolation levels, you will be introduced to later.

4, persistent (Durability)
Persistence means that once a transaction is committed, then changes to the data in the database is permanent, commit the transaction will not be lost even in the case of a database system experienced a failure of the operation . For example we use JDBC database operations, after the transaction is committed method, the user is prompted transaction is complete, when we complete the program execution until prompted, you can identify the transaction has been submitted correctly, even if this time the database there is a problem, it must To complete the full implementation of our business. Otherwise, it would result in significant errors while we see the prompt completion of the transaction, but the database is not because of failure to perform the transaction. This is not allowed.

In the spring using transaction codes need to be configured in the configuration file is almost dead only need to modify the package name to

<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    <!--结合AOP实现事务的植入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <tx:attributes>
            <tx:method name="addUser"/>
            <tx:method name="deleteUser"/>
            <tx:method name="query"/>
            <tx:method name="update"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="txPointCut" expression="execution(* com.Jee.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
Published 53 original articles · won praise 0 · Views 1959

Guess you like

Origin blog.csdn.net/XXuan_/article/details/104099645