Java 之Spring框架注解基本使用

打印 上一主题 下一主题

主题 614|帖子 614|积分 1842

一、注解基本信息

1.声明bean的注解

Spring注解描述@Component组件,没有明确的角色@Service在业务逻辑层使用(service层)@Repository标注在 DAO 类上,这是因为该注解的作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。 Spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架

@Controller定义文档的主体2.注入bean的注解

Spring注解描述@AutowiredSpring提供的工具(由Spring的依赖注入工具(BeanPostProcessor、BeanFactoryPostProcessor)自动注入。)
它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法
@Inject由JSR-330提供@Resource由JSR-250提供3.java配置类相关注解

Spring注解描述@Configuration声明当前类为配置类,相当于xml形式的Spring配置(类上)@Bean注解在方法上,声明当前方法的返回值为一个bean,替代xml中的方式(方法上)@Configuration声明当前类为配置类,其中内部组合了@Component注解,表明这个类是一个bean(类上)@ComponentScan用于对Component进行扫描,相当于xml中的context:component-scan(类上)@WishlyConfiguration为@Configuration与@ComponentScan的组合注解,可以替代这两个注解4.切面(AOP)相关注解

Spring注解描述@Aspect声明一个切面(类上),使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数。@After在方法执行之后执行(方法上)@Before在方法执行之前执行(方法上)@Around在方法执行之前与之后执行(方法上)@PointCut声明切点, 在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(类上)
https://www.cnblogs.com/liaojie970/p/7883687.html
5.@Bean的属性支持

Spring注解描述@Scope设置Spring容器如何新建Bean实例(方法上,得有@Bean)
其设置类型包括:Singleton (单例,一个Spring容器中只有一个bean实例,默认模式),
Protetype (每次调用新建一个bean),
Request (web项目中,给每个http request新建一个bean),
Session (web项目中,给每个http session新建一个bean),
GlobalSession(给每一个 global http session新建一个Bean实例)@StepScope在Spring Batch中还有涉及@PostConstruct由JSR-250提供,在构造函数执行完之后执行,等价于xml配置文件中bean的initMethod@PreDestory由JSR-250提供,在Bean销毁之前执行,等价于xml配置文件中bean的destroyMethod6.@Value注解

@Value 为属性注入值(属性上)
7.环境切换

Spring注解描述@Profile通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。(类或方法上)@ConditionalSpring4中可以使用此注解定义条件话的bean,通过实现Condition接口,并重写matches方法,从而决定该bean是否被实例化。(方法上)8.异步相关

Spring注解描述@EnableAsync配置类中,通过此注解开启对异步任务的支持,叙事性AsyncConfigurer接口(类上)@Async在实际执行的bean方法使用该注解来申明其是一个异步任务(方法上或类上所有的方法都将异步,需要@EnableAsync开启异步任务)9.定时任务相关

Spring注解描述@EnableScheduling在配置类上使用,开启计划任务的支持(类上)@Scheduled来申明这是一个任务,包括cron,fixDelay,fixRate等类型(方法上,需先开启计划任务的支持)10.@Enable*注解说明

这些注解主要用来开启对xxx的支持。
Spring注解描述@EnableAspectJAutoProxy开启对AspectJ自动代理的支持@EnableAsync开启异步方法的支持@EnableScheduling开启计划任务的支持@EnableWebMvc开启Web MVC的配置支持@EnableConfigurationProperties开启对@ConfigurationProperties注解配置Bean的支持@EnableJpaRepositories开启对SpringData JPA Repository的支持@EnableTransactionManagement开启注解式事务的支持@EnableCaching开启注解式的缓存支持11.测试相关注解

Spring注解描述@RunWith运行器,Spring中通常用于对JUnit的支持@ContextConfiguration用来加载配置ApplicationContext,其中classes属性用来加载配置类

二、纯注解开发


1、pom.xml
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>Spring_mybatisDemo</groupId>
  5.     <artifactId>Spring_mybatisDemo</artifactId>
  6.     <version>0.0.1-SNAPSHOT</version>
  7.     <packaging>war</packaging>
  8.     <name />
  9.     <description />
  10.     <dependencies>
  11.         <dependency>
  12.             <groupId>org.springframework</groupId>
  13.             <artifactId>spring-beans</artifactId>
  14.             <version>4.1.7.RELEASE</version>
  15.         </dependency>
  16.         
  17.         
  18.         <dependency>
  19.             <groupId>org.springframework</groupId>
  20.             <artifactId>spring-context</artifactId>
  21.             <version>4.1.7.RELEASE</version>
  22.         </dependency>
  23.         <dependency>
  24.             <groupId>org.springframework</groupId>
  25.             <artifactId>spring-jdbc</artifactId>
  26.             <version>4.1.7.RELEASE</version>
  27.         </dependency>
  28.         
  29.         <dependency>
  30.             <groupId>org.mybatis</groupId>
  31.             <artifactId>mybatis</artifactId>
  32.             <version>3.2.3</version>
  33.         </dependency>
  34.         <dependency>
  35.             <groupId>org.mybatis</groupId>
  36.             <artifactId>mybatis-spring</artifactId>
  37.             <version>1.2.0</version>
  38.         </dependency>
  39.         
  40.         <dependency>
  41.             <groupId>c3p0</groupId>
  42.             <artifactId>c3p0</artifactId>
  43.             <version>0.9.1.2</version>
  44.         </dependency>
  45.         <dependency>
  46.             <groupId>mysql</groupId>
  47.             <artifactId>mysql-connector-java</artifactId>
  48.             <version>5.1.39</version>
  49.         </dependency>
  50.     </dependencies>
  51.     <build>
  52.         <sourceDirectory>${basedir}/src</sourceDirectory>
  53.         <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
  54.         <resources>
  55.             <resource>
  56.                 <directory>${basedir}/src</directory>
  57.                 <excludes>
  58.                     <exclude>**/*.java</exclude>
  59.                 </excludes>
  60.             </resource>
  61.         </resources>
  62.         <plugins>
  63.             <plugin>
  64.                 <artifactId>maven-war-plugin</artifactId>
  65.                 <configuration>
  66.                     <webappDirectory>${basedir}/WebRoot</webappDirectory>
  67.                     <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
  68.                 </configuration>
  69.             </plugin>
  70.             <plugin>
  71.                 <artifactId>maven-compiler-plugin</artifactId>
  72.                 <configuration>
  73.                     <source>1.6</source>
  74.                     <target>1.6</target>
  75.                 </configuration>
  76.             </plugin>
  77.         </plugins>
  78.     </build>
  79. </project>
复制代码
View Code2、配置类
SpringConfig.java
  1. package com.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.Import;
  6. import com.mapper.AdminMapper;
  7. import com.mapper.impl.AdminMapperImpl;
  8. @Configuration
  9. @ComponentScan("com.dao")
  10. @Import(JdbcConfig.class)
  11. public class SpringConfig {
  12.     @Bean
  13.     public AdminMapper AdminMapper1(){
  14.         return new AdminMapperImpl();
  15.     }
  16. }
复制代码
JdbcConfig.java
  1. package com.config;
  2. import java.io.IOException;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.mybatis.spring.SqlSessionFactoryBean;
  5. import org.mybatis.spring.SqlSessionTemplate;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.core.io.ClassPathResource;
  9. import org.springframework.core.io.Resource;
  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  11. import org.springframework.core.io.support.ResourcePatternResolver;
  12. import com.mchange.v2.c3p0.ComboPooledDataSource;
  13. //@Configuration
  14. public class JdbcConfig {
  15.     @Value("jdbc:mysql://localhost:3306/jrbac")
  16.     private String jdbcUrl;
  17.     @Value("com.mysql.jdbc.Driver")
  18.     private String driverClass;
  19.     @Value("jrbac")
  20.     private String user;
  21.     @Value("123456")
  22.     private String password;
  23.    
  24.    
  25.     @Bean
  26.     public ComboPooledDataSource dataSource() throws Exception {
  27.         ComboPooledDataSource dataSource = new ComboPooledDataSource();
  28.         dataSource.setJdbcUrl(jdbcUrl);
  29.         dataSource.setDriverClass(driverClass);
  30.         dataSource.setUser(user);
  31.         dataSource.setPassword(password);
  32.         return dataSource;
  33.     }
  34.    
  35.     @Bean
  36.     public SqlSessionFactoryBean sqlSessionFactory(ComboPooledDataSource dataSource) throws IOException
  37.     {
  38.         SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
  39.         sqlSessionFactory.setDataSource(dataSource);
  40.         sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
  41.         ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
  42.         Resource[] resources = resourceResolver.getResources("classpath:com/dao/*.xml");
  43.         sqlSessionFactory.setMapperLocations(resources);
  44.         return sqlSessionFactory;
  45.     }
  46.    
  47.     @Bean
  48.     public SqlSessionTemplate sqlSession(SqlSessionFactory sqlSessionFactory) throws Exception {
  49.         
  50.         return new SqlSessionTemplate(sqlSessionFactory);
  51.     }
  52. }
复制代码
AdminMapperImpl.java
  1. package com.mapper.impl;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.springframework.stereotype.Component;
  6. import com.entity.Admin;
  7. import com.mapper.AdminMapper;
  8. @Component(value = "AdminMapper1")
  9. public class AdminMapperImpl implements AdminMapper{
  10.     @Resource(name = "sqlSession")
  11.     private SqlSessionTemplate sqlSession;
  12.    
  13.     public void setSqlSession(SqlSessionTemplate sqlSession) {
  14.         this.sqlSession = sqlSession;
  15.     }
  16.     @Override
  17.     public List<Admin> selectAdmin() {
  18.         AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);
  19.         return mapper.selectAdmin();
  20.     }
  21. }
复制代码
AdminMapper.java
  1. package com.mapper;
  2. import java.util.List;
  3. import com.entity.Admin;
  4. public interface AdminMapper {
  5.     List<Admin> selectAdmin();
  6. }
复制代码
adminMapper.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.mapper.AdminMapper">
  6.     <select id="selectAdmin" resultType="com.entity.Admin">
  7.         select * from j_admin
  8.     </select>
  9. </mapper>
复制代码
Test2.java
  1. package com.test;
  2. import java.util.List;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  5. import com.config.SpringConfig;
  6. import com.entity.Admin;
  7. import com.mapper.AdminMapper;
  8. public class Test2 {
  9.     public static void main(String[] args) {
  10.         ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
  11.         AdminMapper adminMapper = (AdminMapper) context.getBean("AdminMapper1");
  12.         List<Admin> admin = adminMapper.selectAdmin();
  13.         for(Admin i : admin){
  14.             System.out.println(i);
  15.         }
  16.     }
  17. }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

伤心客

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表