Java Spring

Spring框架:更快速地开发更高效的开发,融合了多种框架的容器

HelloSpring第一个Spring程序

编写实体类

package com.huang.pojo;

public class User {
    private String Name;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

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

编写配置文件

<?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">

    <!--使用spring来创建对象,在spring这些都称为Bean-->
    <bean id="hello" class="com.huang.pojo.User">
        <property name="name" value="哈喽"/>
    </bean>

</beans>

编写测试类

import com.huang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void text(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User hello = (User) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

Sring调用业务层接口

Dao接口

package com.huang.Dao;

public interface UserDao {
    void getName();
}
package com.huang.Dao;

public class UserDaoImpl implements UserDao{
    @Override
    public void getName() {
        System.out.println("正常的sql");
    }
}
package com.huang.Dao;

public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getName() {
        System.out.println("这是一个mysql");
    }
}

Service接口

package com.huang.service;

public interface UserService {
    void getUser();
}
package com.huang.service;

import com.huang.Dao.UserDao;

public class UserServiceImpl implements UserService{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void getUser() {
        userDao.getName();
    }
}

spring配置文件编写

<?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">

    <!--使用spring来创建对象,在spring这些都称为Bean-->
    <bean id="sql1" class="com.huang.Dao.UserDaoImpl"/>
    <bean id="sql2" class="com.huang.Dao.UserDaoMysqlImpl"/>

    <bean id="UserService" class="com.huang.service.UserServiceImpl">
        <property name="userDao" ref="sql2"/>
    </bean>
</beans>

编写测试类

import com.huang.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void text(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl userService = (UserServiceImpl) context.getBean("UserService");
        userService.getUser();
    }
}

使用有参构造函数编写Spring

package com.huang.pojo;

import java.util.Date;

public class User {
    private int id;
    private String name;
    private Date times;

    public User(int id, String name, Date times) {
        this.id = id;
        this.name = name;
        this.times = times;
    }

    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 Date getTimes() {
        return times;
    }

    public void setTimes(Date times) {
        this.times = times;
    }

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

编写Spring配置文件

<?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">
<!--    <import resource="beans.xml"/>-->
<!--    <import resource="beans2.xml"/>-->
<!--    <import resource="beans3.xml"/>-->

    <bean id="hello1" class="com.huang.pojo.User" name="he1">
        <constructor-arg index="0" value="2"/>
        <constructor-arg index="1" value="小明"/>
        <constructor-arg index="2" value="2021/8/8"/>
    </bean>

    <bean id="hello2" class="com.huang.pojo.User" name="he2">
        <constructor-arg name="id" value="3"/>
        <constructor-arg name="name" value="小兰"/>
        <constructor-arg name="times" value="2021/9/24"/>
    </bean>

    <alias name="hello1" alias="h1"/>
    <alias name="hello2" alias="h2"/>

</beans>

编写测试类

import com.huang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void getHello1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User id = (User) context.getBean("hello1");
        System.out.println(id.toString());
    }
    @Test
    public void getHello2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User id = (User) context.getBean("hello2");
        System.out.println(id.toString());
    }
    @Test
    public void getHello3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User id = (User) context.getBean("he1");
        System.out.println(id.toString());
    }
    @Test
    public void getHello4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User id = (User) context.getBean("h1");
        System.out.println(id.toString());
    }
}

Spring注入方式(Set)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       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="student" class="com.huang.pojo.Student">
        <property name="name" value="张三"/>
        <property name="age" value="38"/>
        <property name="times" value="2021/9/10"/>
    </bean>
    <bean id="user" class="com.huang.pojo.User">
        <!--普通注入-->
        <property name="name" value="小明"/>
        <!--类的注入-->
        <property name="student" ref="student"/>
        <!--数组注入-->
        <property name="books">
            <array>
                <value>语文</value>
                <value>数学</value>
                <value>英语</value>
                <value>物理</value>
            </array>
        </property>
        <!--List注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>看书</value>
                <value>游戏</value>
            </list>
        </property>
        <!--Map注入-->
        <property name="card">
            <map>
                <entry key="1" value="123456"/>
                <entry key="2" value="456789"/>
                <entry key="3" value="147852"/>
            </map>
        </property>
        <!--Set注入-->
        <property name="games">
            <set>
                <value>lol</value>
                <value>cs</value>
                <value>DNF</value>
            </set>
        </property>
        <!--Properties注入-->
        <property name="info">
            <props>
                <prop key="1">asdffs</prop>
                <prop key="2">sisisisis</prop>
                <prop key="3">zaissai</prop>
            </props>
        </property>
    </bean>
    <!--p标签注入-->
    <bean id="user2" class="com.huang.pojo.User" p:name="小兰"/>
    <!--c标签注入-->
    <bean id="user3" class="com.huang.pojo.User" c:name="小强"/>
</beans>

Spring 自动装配Bean

<?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="cat" class="com.huang.pojo.Cat"/>
    <bean id="dog" class="com.huang.pojo.Dog"/>
    <bean id="people" class="com.huang.pojo.People">
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
        <property name="name" value="小明"/>
    </bean>

    <bean id="people1" class="com.huang.pojo.People" autowire="byName">
        <property name="name" value="小明"/>
    </bean>

    <bean id="people2" class="com.huang.pojo.People" autowire="byType">
        <property name="name" value="小明"/>
    </bean>
</beans>

Spring中的注解开发

@Autowired  自动装配通过类型和名字
    如果Autowired 不能唯一自动装配上属性;
@Nullable 字段标记了这个注解 说明这个字段可以null;
@Resource 自动装配通过名字 类型
    
衍生的注解
dao [@Repository]
service [@Service]
controller [@Controller]
这四个注解功能是一样的,都是代表某个类注册到Spring中 装配

Spring中配置aop的三种方式

<?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-->
    <bean id="UserService" class="com.huang.service.UserServiceImpl"/>
    <bean id="BeforeLog" class="com.huang.log.BeforeLog"/>
    <bean id="AfterLog" class="com.huang.log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.huang.service.UserServiceImpl.*(..))"/>

        <aop:advisor advice-ref="BeforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
    </aop:config>
    <!--方式二:自定义类-->
    <bean id="diy" class="com.huang.diy.DiyPoinCut"/>
    <aop:config>
        <!--自定义切面-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.huang.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
    <!--方式三-->
    <bean id="annotation" class="com.huang.diy.AnnotationPointCut"/>
    <!--开启注解支持!-->
    <aop:aspectj-autoproxy/>

</beans>

方法二需要的类

package com.huang.diy;

public class DiyPoinCut {
    public void before(){
        System.out.println("----方法执行前------");
    }
    public void after(){
        System.out.println("------方法执行后-----");
    }
}

方法一种需要的类

package com.huang.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(returnValue);
    }
}
package com.huang.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class BeforeLog implements MethodBeforeAdvice {
    //method: 要执行的目标对象的方法
    //args: 参数
    //target: 目标对象
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + method.getName());
    }
}

测试类

import com.huang.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyText {
    @Test
    public void text(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("UserService", UserService.class);
        userService.select();
    }
}

Mybatis与Spring整合

mybatis配置文件

<?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>
    <!--配置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.huang.pojo"/>
    </typeAliases>
</configuration>

Spring配置文件

<?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">

    <!--DataSoure:使用Spring数据源替换Mybatis的配置-->
    <bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/smbms?useUnicode=true&amp;characterEncoding=utf8&amp;useSSl=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSouce"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/huang/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="blogMapper" class="com.huang.mapper.BlogMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

    <bean id="blogMapper2" class="com.huang.mapper.BlogMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

Mapper接口

package com.huang.mapper;

import com.huang.pojo.Blog;

import java.util.List;

public interface BlogMapper {
    List<Blog> getBlog();
}
<?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.huang.mapper.BlogMapper">
    <select id="getBlog" resultType="Blog">
        SELECT * FROM `school`.`blog`
    </select>
</mapper>

编写Spring调用的类

package com.huang.mapper;

import com.huang.pojo.Blog;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class BlogMapperImpl implements BlogMapper{
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<Blog> getBlog() {
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        return mapper.getBlog();
    }
}

测试类

import com.huang.mapper.BlogMapper;
import com.huang.pojo.Blog;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.List;


public class MyText {
    @Test
    public void getBlog() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-Dao.xml");
        BlogMapper blogMapper = context.getBean("blogMapper", BlogMapper.class);
        List<Blog> blogs = blogMapper.getBlog();
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }
    @Test
    public void getBlog2() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-Dao.xml");
        BlogMapper blogMapper = context.getBean("blogMapper2", BlogMapper.class);
        List<Blog> blogs = blogMapper.getBlog();
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }
}

声明式事务

<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSouce"/>
</bean>

<!--aop:配置事务的切面插入-->
<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.huang.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、付费专栏及课程。

余额充值