Spring_day02

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Spring_day02脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

第一章、注解与包扫描

1. 注解的作用

  和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。

  本质上:所有一切的操作都是Java代码来完成的,XML和注解只是告诉框架中的Java代码如何执行。

  注意:SPRing 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注解进行后续操作。

2. 包扫描

  (1)在xml文件中配置包扫描

    引入schema约束:先引入命名空间,约束文件的位置(自动引入)

    <context:component-scan> 主键扫描器

      属性base-package:指定扫描的包

    <context:component-scan base-package = "com.atguigu"/>

    

  (2)@Component:加在类上,将该类注入IOC容器

      属性:value就是这个对象的id值配置,默认是就是类名,首字母小写

    等价于:<bean class="com.atguigu.ioc.COMmonComponent" id="commonComponent"/>

    创建类:

    @Controller:添加在表现层下

    @Service:添加在业务层中

    @ReposITory:添加在持久层

&nbsp;

 

@Component(value = "myComponent1")
public class CommonComponent {
}

    测试:

  @test
    //测试注解开发,通过id获取对象
    public void testGetBeanId(){
        Object commonComponent = context.getBean("myComponent1");
        System.out.println("commonComponent = " + commonComponent);
    }

 第二章、SpringIOC实现数据表操作(全配置文件)

1. 导入依赖

<!--导入jar包-->
  <dePEndencies>
    <!--
        添加spring框架的jar
        context:上下文,框架核心包
    -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <!--MySQL-->
    <dependency>
      <groupId>mySQL</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!--druid工具包-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.6</version>
    </dependency>
    <!--DBUtils-->
    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.6</version>
    </dependency>
    <!--lomBook-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
      <scope>provided</scope>
    </dependency>

    <!--添加日志jar-->
    <dependency>
      <groupId>LOG4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <!--编译插件,配置信息-->
        <@R_406_1058@uration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>utf-8</encoding>
        </configuration>
      </plugin>
    </plugins>
  </build>

2. 创建DAO层、service层、pojo包

  (1)dao层

public interface AccountDao {
    public void saveAccount(Account account);
}
public class AccountDaoImpl implements AccountDao{
    //使用持久层QueryRUnner对象,对象已经放在IOC容器,注入进来
    private QueryRunner qr;

    public void setQr(QueryRunner qr) {
        this.qr = qr;
    }

    @override
    public void saveAccount(Account account) {
        String sql = "insert into account values(?,?,?)";
        Object[] params = {account.getId(),account.getName(),account.getMoney()};
        try {
            qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

  (2)service层

public interface AccountService {
    public void saveAccount(Account account);
}
public class AccountServiceimpl implements AccountService {
    private AccountDao accountDao;
    
    public AccountServiceImpl(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    
    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
}

  (3)pojo层

@Data
public class Account {
    private Integer id;
    private String name;
    private double money;
}

3. 创建applicationContext.xml文件

  (1)配置DataSource:

      druid配置:DruidDataSource ——> 原始写法:DruidDataSourceFactory.createDataSource(properties)

      c3p0配置:CombopooledDatasource ——> 原始写法:new CombopooledDataSource()

 <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <!--DruidDataSource 对象使用set方法注入,数据库连接信息-->
        <property name="driverclassname" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

 

<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&amp;useSSL=false"/>
        <property name="password" value="root"/>
        <property name="user" value="root"/>
    </bean>

  (2)配置QueryRunner对象

<!--
        配置QueryRunner对象
        private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    -->
    <bean class="org.apache.commons.dbutils.QueryRunner" id="queryRunner">
        <!--注入对象QueryRunner,构造方法注入,注入德鲁伊连接池-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

  (3)配置Dao层、Service层实现类

<!--持久层对象,放在Spring的IOC容器中-->
    <bean class="com.atguigu.dao.AccountDaoImpl" id="accountDao">
        <!--set方法,注入QueryRunner对象-->
        <property name="qr" ref="queryRunner"/>
    </bean>
    <!--业务层对象,放在Spring的IOC容器中-->
    <bean class="com.atguigu.service.AccountServiceImpl" id="accountService">
        <!--构造方法,注入AccountDao对象-->
        <constructor-arg name="accountDao" ref="accountDao"/>
    </bean>

  (4)测试

public class MainTest {
    private ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    //测试IOC操作数据库
    public void testIOCSaveAccount(){
        //获取业务层对象
        AccountService accountService = context.getBean(AccountService.class);
        /*
            创建账户对象,存储数据
            Web开发,数据表单提交,封装数据
        * */
        Account account = new Account();
        account.setName("jack");
        account.setMoney(1000D);
        accountService.saveAccount(account);
    }
}

第三章、SpringAnnotationIOC实现数据表操作(XML半注解)

  整体内容除了dao层、service层对象注入SpringIOC容器中的配置改写为注解的形式外,没有其他位置的变动

  (1)配置依赖,配置maven编译环境(maven-compile-plugin)

  (2)创建applicationContext.xml

      (1)将dao层、service层对象注入SpringIOC容器中的配置改写为注解的形式

      @Autowired:自动装配对象,对象具有唯一性

      @Qualifier:多个接口实现类,挑选一个合格对象进行装配,

          注解属性 value 配置的是对象id唯一标识,与@AutoWired联合使用

      @Resource 实现对象装配,JDK提供,不是Spring框架的注解

          注解属性:name = 配置对象的唯一id值,@Resource = @Autowired + @Qualifier

      (2)配置包扫描

      (3)配置DataSource

      (4)配置QueryRunner

  (3)编写测试类

第四章、纯注解方式操作数据表

1.  创建配置文件类SpringConfig.java类

    @Configuration:指明该类添加注解表明是配置类,取代ApplicationContext.xml

    @ComponentScan(basePackage={"com.atguigu"}):配置包扫描

        包扫描注解配置:@ComponentScan(basePackages={"com.atguigu"}

        String[] basePackages配置要扫描的包,如果是多个包,用","隔开

        <context:component-scan base-package="com.atguigu"/>

    @Import(JdbcConfig.class):引入其他配置类

      属性value 配置另一个类的class对象

    @Bean,Spring框架就会方法的返回值放在IOC容器

      value属性:对象的唯一标识,配置文件中的id,默认就是方法名去掉get,首字母小写

  SpringConfig.java

@Configuration
@ComponentScan(basePackages = {"com.atguigu"})
@Import(JdbcConfig.class)
public class SpringConfig {


}

2.  将SpringConfig.java中数据库的配置信息提取到JdbcConfig.java类中

  (1)@PropertySource:引入外部配置文件

      属性:value 字符串的数组,一个元素

    @Value:定义数据库连接的4个字段的值

  JdbcConfig.java

@PropertySource("db.properties")
public class JdbcConfig {
    /*
        @Value
            定义数据库连接的4个字符

    * */
    @Value("${jdbc.driver}")
    private String dirver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /*
        配置连接池,并注入IOC容器中
        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"></bean>
        注解:@Bean,Spring框架就会方法的返回值放在IOC容器
        @Bean注解:
            value属性:对象的唯一标识,配置文件中的id,默认就是方法名去掉get,首字母小写
    * */
    @Bean(value = "dataSource")
    public DataSource getDataSource() throws PropertyVetoException {
        //创建连接池对象,DataSource接口实现类的对象
        //不要使用多台,应为DataSource没有设置数据库连接信息的方法
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(dirver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /*
        迁移QueryRunner对象
        利用返回值,讲对象放在IOC容器
        将连接池对象,作为方法的参数传递
    * */
    @Bean
    public QueryRunner getQueryRunner(@Qualifier("dataSource")DataSource dataSource){
        QueryRunner queryRunner = new QueryRunner(dataSource);
        return queryRunner;
    }
}

3. db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=root

4. 测试类

public class MainTest {
    //启动Spring框架:定义的配置类启动
    //AnnotationConfigApplicationContext 构造方法,传递配置类的class对象
    private ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
    @Test
    public void test(){
        AccountService accountService = context.getBean(AccountService.class);
        Account account = new Account();
        account.setName("赵");
        account.setMoney(5768D);
        accountService.saveAccount(account);
    }
}

 第五章、Spring框架对Junit的支持

  (1)导入org.springframework.spring-test.jar

  (2)@RunWith:Spring集成对junit支持:直接注入对象

    @RunWith注解:

      Junit底层有一个类(Main方法启动的)

        Spring提供了一个类,取代了Junit底层的类

      @RunWith注解的属性:value 是class类,传递一个类的class对象

   通过配置文件启动,或通过配置类启动

    @ContextConfiguration:junit环境下使用,表明配置文件启动,还是配置启动

      注解属性:String[] locations() defauls{}:配置文件启动

      注解属性:Class<?>[] classes() default{}:配置类启动

 

  测试类·

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
//配置文件方法启动的配置
//@ContextConfiguration(locations = "classpath:application.xml")
public class MainTest {
    @Autowired
    private AccountService accountService;
    @Test
    public void test(){
        Account account = new Account();
        account.setName("赵云");
        account.setMoney(5768D);
        accountService.saveAccount(account);

    }
}

 

脚本宝典总结

以上是脚本宝典为你收集整理的Spring_day02全部内容,希望文章能够帮你解决Spring_day02所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。