spring2-ioc使用注解的方式

  1. 注解的解释
    1)用于创建对象的:他们的作用就和xml配置-文件中编写一个标签实现的功能
    a. component:作用:用于把对象存入spring容器中
    属性:value:用于指定bean的id,默认值时当前类名,首字母小写
    b.Controller:一般用于表现层
    c.Service:一般用于业务层
    d:Repository:一般用于持久层
    bdc的作用和a的作用时一样的,只是为了更加的清晰
    2)用于注入数据的:他们的作用就和在xml配置文件中的bean标签中写一个 标签是一样的。
    Autowired:作用:自动按照类型注入,只要有唯一的一个bean对象类型和注入的变量类型匹配,就可以注入成功,如果没有则报错,如果有多个就需要@Qualifier。出现位置:可以是变量也可以是方法上,此时sett方法可以不用了
    @Qualifier:在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowire 一起使用;但是给方法参数注入时,可以独立使用。 属性: value:指定 bean 的 id。
    @Resource :作用:直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。属性: name:指定 bean 的 id。
    上面三个只能注入bean类型的,基本数据类型和String无法使用
    @Value 作用: 注入基本数据类型和 String 类型数据的 属性: value:用于指定值
    3) 用于改变作用范围的: 相当于:<bean id="" class="" scope="">
    @Scope 作用:指定 bean 的作用范围。 value:指定范围的值。 取值:singleton prototype request global-session
    4)和生命周期相关的:相当于:<bean id="" class="" init-method="" destroy-method="" />
    @PostConstruct 初始化方法。
    @PreDestroy 销毁方法。
    2.新注解:
    1)@Configuration 作用: 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。 属性: value:用于指定配置类的字节码
    2)@ComponentScan 用于指定 spring 在初始化容器时要扫描的包属性: basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。
    3)@Bean :作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器属性:name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)
    4)@PropertySource 作用:用于加载.properties 文件中的配置 属性: value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:
    5)@Import :作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问 题。
  2. Spring 整合 Junit 作用:
    解放
 ApplicationContext cp =  new AnnotationConfigApplicationContext(SpringConfigu.class);
 IaccountService accountService = cp.getBean("accountService", IaccountService.class);
1) 在pom坐标中导入
 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

2)在测试类中使用@RunWith 注解替换原有运行器 @RunWith(SpringJUnit4ClassRunner.class)
3)使用@ContextConfiguration 指定 spring 配置文件的位置 @ContextConfiguration(classes= SpringConfigu.class)
也可以是xml文件@ContextConfiguration(locations= {“classpath:bean.xml”})

代码的实现:

  1. 结构图
    在这里插入图片描述
    maven导入的pom.xml坐标
<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>demo02_spring_curd2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
  1. serviceImpl的实现类
@Component("accountService")
public class IaccountServiceImpl implements IaccountService
{
    
    
    @Autowired
    private IaccountDao accDao;

    public List<account> findAll() throws SQLException {
    
    
        return accDao.findAll();
    }

    public account findById(Integer id) throws SQLException {
    
    
        return accDao.findById(id);
    }

    public void updateAcc(account acc) throws SQLException {
    
    
        accDao.updateAcc(acc);
    }

    public void deleteById(Integer id) throws SQLException {
    
    
        accDao.deleteById(id);
    }

    public void insert(account acc) throws SQLException {
    
    
        accDao.insert(acc);
    }
}
  1. accountImpl的实现类
@Component("accDao")
public class IaccountDaoImpl implements IaccountDao {
    
    

    @Autowired
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
    
    
        this.runner = runner;
    }

    public List<account> findAll() throws SQLException {
    
    
        System.out.println("222222");
        List<account> query = runner.query("select *from account", new BeanListHandler<account>(account.class));
        System.out.println(query);

        return  query;
    }

    public account findById(Integer id) throws SQLException {
    
    
        return runner.query("select *from account where id=?",new BeanHandler<account>(account.class),id);
    }

    public void updateAcc(account acc) throws SQLException {
    
    
        runner.update("update account set name=?,money=? where id=?",acc.getName(),acc.getMoney(),acc.getId());
    }

    public void deleteById(Integer id) throws SQLException {
    
    
        runner.update("delete *from account where id =?",new BeanHandler<account>(account.class),id);
    }

    public void insert(account acc) throws SQLException {
    
    
        runner.update("insert into account values(?,?)",acc.getName(),acc.getMoney());
    }


}
  1. pojo
public class account {
    
    
    private Integer id;
    private  String name;
    private  float money;

    public Integer getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

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

    public float getMoney() {
    
    
        return money;
    }

    public void setMoney(float money) {
    
    
        this.money = money;
    }

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

5.注解的配置

@Configuration
@ComponentScan("lml")//用于指定spring在初始化容器时要扫描的包
@Import({
    
    jdbcConfig.class})
public class SpringConfigu {
    
    
}
@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class jdbcConfig {
    
    
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean(name="dataSource")
    public DataSource createDataSource() throws PropertyVetoException {
    
    
        ComboPooledDataSource ds = new ComboPooledDataSource();
        System.out.println("111");
        ds.setUser(username);
        ds.setPassword(password);
        ds.setDriverClass(driver);
        ds.setJdbcUrl(url);

        System.out.println(username);System.out.println(password);System.out.println(driver);
        System.out.println(url);
        return ds;
    }
    @Bean("runner")//当使用注解时,如果有参数,spring会查找
    public QueryRunner createQueryRunner(DataSource dataSource)
    {
    
    
        return new QueryRunner(dataSource);
    }
}
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springOne?serverTimezone=UTC
jdbc.username=root
jdbc.password=admin

6.Spring整合junit的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= SpringConfigu.class)
public class testCURD2 {
    
    
    IaccountService accountService=null;
    @Test
    public void findAll()
    {
    
    
//       ApplicationContext cp =  new AnnotationConfigApplicationContext(SpringConfigu.class);
//        IaccountService accountService = cp.getBean("accountService", IaccountService.class);
        /*ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("bean.xml");
        IaccountService accountService = classPathXmlApplicationContext.getBean("accountService", IaccountService.class);*/
        try {
    
    
            List<account> all = accountService.findAll();
            System.out.println(all);
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        }
    }
}

总结:我的mysql是8.0版本的,在配置上老是出错,测试的时候吃了大亏了,不然昨天这条就更新了,还有一些注解的方法,还是得多用,个人觉得xml配置还是比较好理解的,比较好找映射文件
粘贴一张anno和xml的比较
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46809332/article/details/115681856