• Spring框架(4)--Spring注解开发


    Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替核心配置文件中的依赖注入可以达到简化配置的效果,提高开发效率。

    几个常用的原始注解:

    创建对象的注解:

    注解说明
    @Component 使用在类上,用于实例化Bean
    @Controller 使用在web层类上,用于实例化Bean
    @Service 使用在service层类上,用于实例化Bean
    @Repository 使用在dao层类上用于,实例化Bean

    依赖注入的注解:

    注解说明
    @Autowired 根据类型依赖注入,如果找到多个,则根据变量名依赖注入
    @Qualifier 与@Autowired一起使用,用于根据名称进行依赖注入
    @Resource 相当于@Autowired+@Qualifier,按照名称进行注入
    @Value 注入普通属性。一般用于获取properties中的key,然后注入成员变量中

    作用范围的注解:

    注解说明
    @Scope 两个取值:“prototype” -> 多例的,“singleton” -> 单例的(默认)

    其他注解:

    注解说明
    @PostConstruct 被标注的方法,在对象被创建的时候执行
    @PreDestroy 被标注的方法,在对象被销毁的时候执行

    等等等等,但是使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:

      非自定义的Bean的配置:<bean>

      加载properties文件的配置:<context:property-placeholder>

      组件扫描的配置:<context:component-scan>

      引入其他文件:<import>

    还有一些Spring的新注解:Spring所谓的新注解,就是用来完全替代Spring的配置文件用的。

    注解说明
    @Configuration 用于指定当前类是一个 Spring配置类,当创建容器时会从该类上加载注解
    @ComponentScan 用于指定 Spring 在初始化容器时要扫描的包。
    @Bean 使用在方法上,标注将该方法的返回值存储到 Spring 容器中
    @PropertySource 用于加载.properties 文件中的配置
    @Import 用于导入其他配置类

     案例仅供参考:

    //表示该类是一个Spring的配置类,用来存放spring的配置信息
    @Configuration    
    public class SpringConfiguration {
        
    }
    //用于指定 Spring 在初始化容器时要扫描的包。   
    //相当于xml配置时的`<context:component-scan base-package="com.itheima"/>`
    
    @Configuration
    @ComponentScan("com.itheima")        
    public class SpringConfiguration {
        
    }
    //用于导入其他的配置类 
    //相当于xml配置时的`<import resource="classpath:applicationContext-dao.xml"/>`
    
    @Configuration
    @ComponentScan("com.itheima")
    @Import({DataSourceConfiguration.class})
    public class SpringConfiguration {
    }
    //用于properties配置文件
    //相当于xml配置时的`<context:property-placeholder location="classpath:jdbc.properties"/>`
    
    @PropertySource("classpath:jdbc.properties")
    public class DataSourceConfiguration {
        @Value("${jdbc.driver}")
        private String driver;
        
        @Value("${jdbc.url}")
        private String url;
        
        @Value("${jdbc.username}")
        private String username;
        
        @Value("${jdbc.password}")
        private String password;
    }
    //使用在方法上,Spring会自动执行该方法,并把方法返回的对象,存储在spring容器中
    
    @Bean("dataSource")
    public DataSource getDataSource() throws PropertyVetoException { 
        ComboPooledDataSource ds = new ComboPooledDataSource(); 
        ds.setDriverClass(driver);
        ds.setJdbcUrl(url);
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    } 

    测试新注解:

    @Test
    public void testAnnoConfiguration() throws Exception {
        //根据配置类SpringConfiguration.class,获取Spring的核心容器
        ApplicationContext ac = 
                new AnnotationConfigApplicationContext(SpringConfiguration.class);
        
        //获取userService对象
        UserService userService = (UserService)ac.getBean("userService");
        userService.save();
        
        //获取dataSource对象
        DataSource dataSource = (DataSource)ac.getBean("dataSource");
        Connection connection = dataSource.getConnection(); 
        System.out.println(connection);
    }

    使用注解开发的步骤:

    1.导入坐标:因为我们采用的是C3P0,所以要导入

     1      <dependency>
     2             <groupId>c3p0</groupId>
     3             <artifactId>c3p0</artifactId>
     4             <version>0.9.1.2</version>
     5         </dependency>
     6         <dependency>
     7             <groupId>mysql</groupId>
     8             <artifactId>mysql-connector-java</artifactId>
     9             <version>5.1.47</version>
    10         </dependency>
    11         <dependency>
    12             <groupId>org.springframework</groupId>
    13             <artifactId>spring-jdbc</artifactId>
    14             <version>5.0.5.RELEASE</version>
    15         </dependency>

    2.编写实现功能的接口和类:

     1 public interface UserService {
     2     public List<User> findAll() throws SQLException;
     3 }
     4 
     5 
     6 
     7 @Service
     8 public class UserService implements com.itcast.Service.UserService {
     9 
    10     @Autowired//注解注入
    11     private UserDao userDao;
    12 
    13     public List<User> findAll() throws SQLException {
    14         List<User> users = userDao.findAll();
    15         return users;
    16     }
    17 }
    //接口:
    public interface UserDao {
        public List<User> findAll() throws SQLException;
    }
    
    
    //实现类:
    @Repository
    public class UserDaoImpl implements UserDao {
    
        @Autowired
        private DataSource dataSource;
    
        public List<User> findAll() throws SQLException {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            List<User> users = jdbcTemplate.query("select * from userform", new BeanPropertyRowMapper<User>(User.class));
            return users;
        }
    }

    3.配置核心配置文件applicationContext:

    <?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.itcast"></context:component-scan>
    
        <!--配置C3P0链接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///daynov06"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        
    </beans>

    4.编写测试类:

     1 public class Demo1 {
     2     public static void main(String[] args) throws SQLException {
     3 
     4         //读取配置文件
     5         ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
     6         //从spring中获取目标对象
     7         UserService bean = app.getBean(UserService.class);
     8         //调用方法
     9         List<User> all = bean.findAll();
    10         for (User user : all) {
    11             System.out.println(user);
    12         }
    13 
    14     }
    15 }

    完成测试。

    其他的注解可以查看功能相应的进行练习。

  • 相关阅读:
    leetcode 851. Loud and Rich
    674. 最长连续递增序列
    896. 单调数列
    905. 按奇偶排序数组
    917. 仅仅反转字母
    922. 按奇偶排序数组 II
    925. 长按键入
    929. 独特的电子邮件地址
    933. 最近的请求次数
    自己动手丰衣足食写java贪吃蛇
  • 原文地址:https://www.cnblogs.com/j9527/p/12032054.html
Copyright © 2020-2023  润新知