spring基于注解的IOC配置 知识点

摘要:
@Service:一般用于业务层的注解。作用和在spring的xml配置文件中的:属性:Value:用于指定要扫描的包。@Configuration@ComponentScanpublicclassSpringConfiguration{}@Bean:该注解只能写在方法上,将方法的返回值作为一个bean,并且放入spring容器。

明确:注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦合。只是配置的形式不一样。

配置注解扫描的包:声明到指定的包下去进行扫描,如果发现类上有对应的注解,将其装配到容器中

<context:component-scan base-package="cn.XXX"></context:component-scan>

用于创建对象的(装配bean)注解:

作用:把资源让spring来管理。相当于在xml中配置一个bean。

相当于:<bean id="" class=""></bean>

@Component注解:相当于配置了<bean>标签

value = "XXX":相当于配置了bean标签的id属性,单独配置value时,可以省略value。如果不指定value属性,默认bean的id是当前类的类名。首字母小写。

@Component的三个衍生注解:

@Controller:一般用于表现层的注解。

@Service:一般用于业务层的注解。

@Repository:一般用于持久层的注解。

它们的作用及属性和@Component都是一模一样的。它们只不过是提供了更加明确的语义化。

用于注入数据的注解:

相当于: <property name="" ref=""></property>   <property name="" value=""></property>

@Autowired:

作用:1.自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他bean类型。

2.当有多个类型匹配时,默认使用要注入的对象的变量名称作为bean的id,在spring容器查找,找到了也可以注入成功。找不到就报错。

@Qualifier:

作用:在自动按照类型注入的基础之上,再按照Bean的id注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。

属性:value:指定bean的id。

@Resource:

作用:直接按照Bean的id注入。它也只能注入其他bean类型。

属性:name:指定bean的id。 单独的name也不能省略.

@Value:

作用:1.注入基本数据类型和String类型数据的  eg:@value("zhangsan")

2.在加载外部资源文件的前提下,它可以获取外部资源文件的数据.  eg:@value("${jdbc.url}")

属性:value:用于指定值

作用域相关的注解:

相当于:<bean id="" class="" scope="">

@Scope:

作用:指定bean的作用范围。

属性:value:指定范围的值。  取值:singleton(单例) prototype(多例) request session globalsession  默认:singleton

和生命周期相关的注解:

@PostConstruct:

作用:用于指定初始化方法。 eg:

@PostConstruct
public voidstart(){
  System.out.println("初始化方法执行了");  
}

@PreDestroy:

作用: 用于指定销毁方法。 eg:

@PreDestroy
public voidend(){
  System.out.println("销毁方法执行了");  
}

基于xml配置和基于注解配置:

注解的优势:配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。

XML的优势:修改时,不用改源码。

纯注解配置:

写一个类用来代替xml配置文件,这样就可以脱离xml了,实现纯注解的配置

和配置类相关的注解:

@Configuration:

作用:用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。

获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)

eg: ApplicationContext ac = newAnnotationConfigApplicationContext(有@Configuration注解的类.class);

@ComponentScan:

作用:用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的:<context:component-scan base-package="XXX"></context:component-scan>

属性:Value(单独使用可省略):用于指定要扫描的包。和标签中的basePackages属性作用一样。

@Configuration
@ComponentScan("cn.xxx")
public classSpringConfiguration {

} 

@Bean:

该注解只能写在方法上,将方法的返回值作为一个bean,并且放入spring容器

属性:name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)如果不指定id,那么它默认方法名作为id

  @Bean(name="dataSource")
    public DataSource createDataSource() throwsException{
        ComboPooledDataSource ds = newComboPooledDataSource();
        ds.setDriverClass("com.mysql.jdbc.Driver");
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/xxx");
        ds.setUser("root");
        ds.setPassword("root");
        returnds;
    }
  @Bean(name="queryRunner")  //如果queryRunner是按类型注入的(按类型注入说明只有一个类型匹配)即@@Autowired那么此时这里可以不指定name即@Bean
    public QueryRunner createQueryRunner(@Qualifier("dataSource")DataSource dataSource){
        
        return newQueryRunner(dataSource);
    }

  @Bean(name="dataSource")  //也可以只写@Bean,这时上面@Qualifier("dataSource")也可以不写,只有一个类型匹配时候,是按照类型注入的.有多个类型匹配时则必须指定name即bean的id.
    public DataSource createDataSource() throwsException{
        ComboPooledDataSource ds = newComboPooledDataSource();
        ds.setDriverClass("com.mysql.jdbc.Driver");
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/xxx");
        ds.setUser("root");
        ds.setPassword("root");

@PropertySource:

作用:用于加载.properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。

属性:value[ ]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:

@PropertySource(value = { "classpath:jdbc.properties" })
public classJdbcConfig {
   @Value("${jdbc.driver}")
    privateString driverClass;
    @Value("${jdbc.url}")
    privateString url;
   @Value("${jdbc.username}")
    privateString username;
   @Value("${jdbc.password}")
    privateString password;

   @Bean(name = "dataSource")
    public DataSource createDataSource() throwsException {
        ComboPooledDataSource ds = newComboPooledDataSource();
        ds.setDriverClass(driverClass);
        ds.setJdbcUrl(url);
        ds.setUser(username);
        ds.setPassword(password);
        returnds;
    }
}

@Import:

作用:用于导入其他配置类,在引入其他配置类时,其他类上可以不用再写@Configuration注解。当然,写上也没问题。

属性:value[ ]:用于指定其他配置类的字节码。

eg:
@Configuration
@ComponentScan("xxx")
@Import(value = { JdbcConfig.class })
public classSpringConfiguration {

}

综合eg:

@PropertySource(value = { "classpath:jdbc.properties"})  //数组可以引入多个.properties  eg:@PropertySource(value = { "classpath:jdbc.properties", "aaa.properties", "bbb.properties", ...})
public classJdbcConfig {

    @Value("${jdbc.driver}")
    privateString driverClass;
    @Value("${jdbc.url}")
    privateString url;
    @Value("${jdbc.username}")
    privateString username;
    @Value("${jdbc.password}")
    privateString password;

    @Bean(name = "createQueryRunner")
    public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource) {
        return newQueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource() throwsPropertyVetoException {
        ComboPooledDataSource dataSource = newComboPooledDataSource();
        dataSource.setDriverClass(driverClass);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        returndataSource;
    }
}
@Configuration
@ComponentScan("xxx")
@Import(value = { JdbcConfig.class})  //数组可以引入多个.class   eg:@Import(value = { JdbcConfig.class, aaa.class, bbb.class,...})
public classSpringConfiguration {
}

Spring整合junit:

junit给我们暴露了一个注解,可以让我们替换掉它的运行器。这时,我们需要依靠spring框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。

涉及的注解:

@RunWith:

作用:替换掉junit的运行器,换成一个可以初始化spring容器的运行器。

属性:value:单独配置时,value属性名称可以省略,配置SpringJUnit4ClassRunner.class来代替原来junit的运行器

@ContextConfiguration:

作用:加载配置类或者xml配置文件,创建容器

属性:value[ ]:用来指定xml配置文件的路径

class[ ]: 用来指定配置类

使用上面的两个注解,需要导入spring-test的依赖

eg:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public classIAccountServiceTest {   
    @Autowired
    privateIAccountService accountService;   
    @Test
    public voidtestSaveAccount() {
        //ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //IAccountService accountService = (IAccountService) ac.getBean("accountService");
        Account account = newAccount();
        account.setName("admin1");
        account.setMoney(1000f);
        accountService.saveAccount(account);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringConfiguration.class })
public classIAccountServiceTest {
    @Autowired
    privateAccountController accountController;
    @Test
    public voidtestSaveAccount() {
        Account account = newAccount();
        account.setName("admin8");
        account.setMoney(3000f);
        accountController.saveAccount(account);
    }
}

免责声明:文章转载自《spring基于注解的IOC配置 知识点》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇浅谈“微服务”从PDF中提取信息----PDFMiner下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Spring batch学习 (1)

          Spring Batch 批处理框架 埃森哲和Spring Source研发                          主要解决批处理数据的问题,包含并行处理,事务处理机制等。具有健壮性 可扩展,和自带的监控功能,并且支持断点和重发。让程序员更加注重于业务实现。           Spring Batch 结构如下      ...

Weblogic12c 单节点安装

第一节weblogic12c 的安装 WebLogic除了包括WebLogic Server服务器之外,还包括一些围绕WebLogic的产品,习惯上我们说的WebLogic是指WebLogic Server。WebLogic是美国bea公司出品的一个application server确切的说是一个基于Javaee架构的中间件,BEA WebLogi...

spring自动注入的三种方式

所谓spring自动注入,是指容器中的一个组件中需要用到另一个组件(例如聚合关系)时,依靠spring容器创建对象,而不是手动创建,主要有三种方式: 1. @Autowired注解——由spring提供 2. @Resource注解——由JSR-250提供 3. @Inject注解——由JSR-330提供   @Autowired注解的使用方法 @Tar...

spring boot 和 spring mvc 使用 jackson 包处理 忽略 null 字段返回

spring boot 和 spring mvc 使用 jackson 包处理 忽略 null 字段返回 springmvc 框架默认使用 jackson 出来 json 返回,fastjson 默认是不序列化输出 null 字段的,而 jackson 默认则是输出 null 字段。 xml 配置 spring mvc 的 json 返回忽略 null 字...

JAVA连接数据库

运行如下Java程序,学会JAVA连接数据库的方法。。 import java.sql.*; public class Test { public static void main(String[] srg) { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载...

[mysql] mysql批量操作时性能优化

--------------------------------结论--------------------------------- MySql 非批量10万条记录,5700条/秒 MySql 批量(batch)10万条记录,62500条/秒 oracle 非批量插入10万条记录, 4464 条/秒 oracle 批量 (batch)插入10万条记录,...