Spring 学习笔记

Spring学习

Spring是一个轻量级控制反转IOC和面向切面编程AOP的框架

Spring Boot 快速开发的脚手架

Spring Cloud 基于Springboot实现

学习SpringBoot的前提掌握Spring 以及SpringMVC

Spring中文文档:Spring Framework 5.1.3.RELEASE 中文文档 | Docs4dev

IOC基本实现(DI注入):

代码忘保存了 略

HELLO SPRING:

pojo:

package com.su.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

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

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="Hello" class="com.su.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>


</beans>

Test:

import com.su.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello) context.getBean("Hello");
        System.out.println(hello.toString());

    }
}

image-20210309133541050

@AutoWired(本质是byType):

image-20210309162252051

package com.su.pojo;

public class Cat {
    public void shout(){
        System.out.println("miao");
    }
}
package com.su.pojo;

public class Dog {
        private String name;

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

    public String getName() {
        return name;
    }

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

    public void shout(){
            System.out.println(name+"wang");
        }


}

package com.su.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class People {
//还可以用@Resource(name="")注解
    private String name;
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value="Dog1")
    private Dog dog;

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", cat=" + cat +
                ", 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;
    }

    public Dog getDog() {
        return dog;
    }

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

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: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:annotation-config/>
    <bean id="People" class="com.su.pojo.People"/>
    <bean id="Cat" class="com.su.pojo.Cat"/>
    <bean id="Dog" class="com.su.pojo.Dog">
        <property name="name" value="dog"/>
    </bean>
    <bean id="Dog1" class="com.su.pojo.Dog">
        <property name="name" value="dog1"/>
    </bean>

</beans>

image-20210309163045834

自动扫描包:

@Component 一个意思的注解:

@Repository(Dao)

@Service(service)

@Controller(Controller)

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: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.su"/>
    <context:annotation-config/>


</beans>

AOP:

实现前线maven加载:

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>

老老实实的:

log:

package com.su.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AopAfter implements AfterReturningAdvice {
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("之后打印");
    }
}
package com.su.log;

import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class AopBefore implements MethodBeforeAdvice {

    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("之前打印");
    }
}

接口:

package com.su.service;

public interface UserSerivce {
    public void add();
    public void delete();
}

实现类:

package com.su.service;

public class UserServiceimp implements UserSerivce {
    public void add() {
        System.out.println("添加完成");
    }

    public void delete() {
        System.out.println("删除完成");
    }
}

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

    <bean id="userService" class="com.su.service.UserServiceimp"/>
    <bean id="logbf" class="com.su.log.AopBefore"/>
    <bean id = "logaf" class="com.su.log.AopAfter"/>
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.su.service.UserServiceimp.*(..))"/>

        <aop:advisor advice-ref="logbf" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="logaf" pointcut-ref="pointcut"/>
     </aop:config>


</beans>

测试类:

import com.su.service.UserSerivce;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Bean.xml");
        UserSerivce userservice = (UserSerivce) applicationContext.getBean("userService");
        userservice.add();
        userservice.delete();
    }

}

image-20210311181355486

自定义类:

log类:

package com.su.log;

public class DiyAop {
    public void Before(){
        System.out.println("============之前");
    }
    public void After(){
        System.out.println("============之后");
    }

}

xml配置:

<aop:aspect ref="logDiy">
    <aop:pointcut id="pointcut" expression="execution(* com.su.service.UserServiceimp.*(..))"/>
    <aop:before method="Before" pointcut-ref="pointcut"/>
    <aop:after method="After" pointcut-ref="pointcut"/>
</aop:aspect>

image-20210311182857578

用注解实现:

xml:

<bean id = "Diyaopzhujie" class="com.su.log.DiyAopzhujie"/>
<aop:aspectj-autoproxy/>

class:

package com.su.log;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class DiyAopzhujie {
    @Before("execution(* com.su.service.UserServiceimp.*(..))")
    public void Before(){
        System.out.println("============之前");
    }
    @After("execution(* com.su.service.UserServiceimp.*(..))")
    public void After(){
        System.out.println("============之后");
    }
}

整合mybatis:

导包:

注意spring和mybatis的版本号

image-20210312170459840

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Spring-study</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Spring-06-Mybatis</artifactId>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

mapper:

package com.su.mapper;

import com.su.pojo.User;

import java.util.List;

public interface UserMapper {
     List<User> getUserList();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.su.mapper.UserMapper">
    <select id="getUserList" resultType="com.su.pojo.User" >
        select * from demo.user
    </select>


</mapper>
package com.su.mapper;

import com.su.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImp implements UserMapper {
    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> getUserList() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

        return userList;
    }
}

实体类:

package com.su.pojo;

import lombok.Data;

public class User {
    private int userid;
    private String username;
    private String userpassword;
    private String userpic;
    private String userpower;
    private String useraddress;

    public User() {
    }

    public User(int userid, String username, String userpassword, String userpic, String userpower, String useraddress) {
        this.userid = userid;
        this.username = username;
        this.userpassword = userpassword;
        this.userpic = userpic;
        this.userpower = userpower;
        this.useraddress = useraddress;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpassword() {
        return userpassword;
    }

    public void setUserpassword(String userpassword) {
        this.userpassword = userpassword;
    }

    public String getUserpic() {
        return userpic;
    }

    public void setUserpic(String userpic) {
        this.userpic = userpic;
    }

    public String getUserpower() {
        return userpower;
    }

    public void setUserpower(String userpower) {
        this.userpower = userpower;
    }

    public String getUseraddress() {
        return useraddress;
    }

    public void setUseraddress(String useraddress) {
        this.useraddress = useraddress;
    }

    @Override
    public String toString() {
        return "User{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", userpassword='" + userpassword + '\'' +
                ", userpic='" + userpic + '\'' +
                ", userpower='" + userpower + '\'' +
                ", useraddress='" + useraddress + '\'' +
                '}';
    }
}

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
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--    datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/demo?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--    sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/su/mapper/UserMapper.xml"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <typeAliases>
      <package name="com.su.pojo"/>
  </typeAliases>

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

    <import resource="applicationContext.xml"/>

    <bean id="userMapper" class="com.su.mapper.UserMapperImp">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>
</beans>

test:

import com.su.mapper.UserMapper;
import com.su.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test1 {
    @Test
    public void testv(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springDao.xml");
        UserMapper userMapper = applicationContext.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.getUserList()) {
            System.out.println(user);
        }

    }


}

甚至可以去掉注入:

更快捷的方法:

    <import resource="applicationContext.xml"/>

    <bean id="userMapper" class="com.su.mapper.UserMapperImp">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>
    <bean id ="UserMapper2" class="com.su.mapper.UserMapper2Impl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>
package com.su.mapper;

import com.su.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapper2Impl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUserList() {
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }
}

aop事务管理:

最好不要加中文注释 天天报错

建议删除中文注释

<!--    aop事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


<!--    结合Aop食物的织入-->
<!--    配置事物的传播特性  propagation传播-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!-- 配置事物   -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.su.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值