Spring_Ioc注解方式使用

1、基于注解的配置

1.1、怎么用注解将类注册到IOC

1、设置包扫描<context:component-scan
2、在对应的类名加上对应的注解
注册好的bean将会把类名的首字母变成小写作为bean的名称

1.2、component-scan详解

<!--
    @Controller 标记在控制层的类注册为Bean注解
    @Service    标记在业务逻辑层的类注册为Bean注解
    @Repository 标记在数据访问层的类注册为Bean注解
    @Component  标记在非三层的普通的类注册为Bean注解

    不是非要每个层都对应相应的注解:    1、可读性增强
                                     2、利于Spring管理
    component-scan  包扫描,设置需要扫描的包
    type:   1、annotation    默认,根据注解完成扫描包的排除\包括
            2、assignable    根据类的完整性限定名设置排除\包括
            3、aspectj       根据切面表达式设置排除\包括  一般不使用
            4、regex         根据正则表达式设置排除\包括
            5、custom        接口的自定义实现设置排除\包括
    排除扫描 exclude-filter 设置需要排除扫描的选项
    包含扫描 include-filter 设置需要包含扫描的类
    use-default-filters 设置默认是否扫描哪些类
        如果为true,则默认扫描Controller,Service,Repository,Component这些注解
        如果为false,则不扫描Controller,Service,Repository,Component这些注解
-->
<context:component-scan base-package="cool.ale" use-default-filters="false">
    <context:include-filter type="assignable" expression="cool.ale.controller.UserController"/>
</context:component-scan>

1.3、@value

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {

    /**
     * 使用@Value设置依赖注入的属性
     * 1、写硬编码值
     * 2、写${}、#{}
     */
    @Value("阿乐")
    private String name;

    public String getName() {
        return name;
    }

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

1.4 Autowired(自动注入)

/**
 * 使用@Autowired自动注入
 * 这里是给接口注册
 * 因为这个接口的实现类(UserServiceImpl)在ioc的bean中,所以也会匹配到
 * byType byName
 * 默认优先使用byType
 * 如果匹配到多个,则会用名字去匹配
 * 如果名字也没有匹配到,则会报错
 * 		如果有多个,而且名字也没有匹配到的解决办法
 * 		1、修改属性的名字
 * 		2、增加value属性,value属性可以省略
 * 		3、也可以使用Qualifier注解根据里面的value值去匹配
 * 		4、@Primary 设置主要注入的bean
 * 		5、使用泛型注入Bean
 */
@Autowired
@Qualifier("userServiceImpl")
UserService userService;


@Service("UserService")
@Primary
public class UserServiceImpl implements UserService {
}

@Service(value="UserService")
public class UserServiceImpl implements UserService {
}


// 泛型
// BaseService
public interface BaseService<T> {
    T getBean();
}


//UserServiceImpl
@Service
public class UserServiceImpl implements BaseService<User> {

    public User getBean() {
        System.out.println("查询UserServiceImpl");
        return null;
    }
}


//RoleServiceImpl
@Service
public class RoleServiceImpl implements BaseService<Role> {

    public Role getBean() {
        System.out.println("查询RoleServiceImpl");
        return null;
    }
}



//UserController
@Controller
public class UserController {
    @Autowired
    BaseService<User> baseService;

    public void getUserName() {
        baseService.getBean();
    }
}


//test
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
UserController userController = ioc.getBean(UserController.class);
userController.getUserName();


1.4.1、@Resource和@Autowired的区别

1、@Resource依赖于jdk,@Autowired依赖于Spring
2、@Resource优先根据名字匹配,@Autowired优先根据于类型匹配

1.4.2、bean的生命周期注解

@PostConstruct:Bean的初始化。
@PreDestroy:Bean的销毁

2、基于JavaConfig的配置(纯注解)

2.1、什么是JavaConfig

JavaConfig原来是Spring的一个子项目,它通过Java类的方式提供Bean的定义信息,在Spring4的版本中,JavaConfig已经成为Spring4的核心功能。

2.2、注解详解

2.2.1、@Configuration

用户标记一个Spring的配置类,之前是根据xml启动Spring的上下文,相当于xml文件中的。
下面这段代码相当于是把这个类注册成为一个spring.xml文件。

@Configuration
public class IocJavaConfig {

}

2.2.2、@ComponentScan

包扫描的类

@Configuration
@ComponentScan(basePackages = "cool.ale")
public class IocJavaConfig {

}

2.2.3、@Bean

引入第三方的bean
例如Controller注解是将类将给Spring的ioc去管理去new,Bean注解是我们自己new好之后交给Spring,我们可以自主的干预类的创建。
别名可设置多个,例如下面代码

@Bean(initMethod = "init",name={"dataSource","dd"})
public DruidDataSource dataSource(){
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/sam");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    return dataSource;
}

2.2.4、引入外部资源文件

//db.properties
mysql.username=rootlala
mysql.password=root
mysql.url=jdbc:mysql://localhost:3306/sam
mysql.driver=com.mysql.jdbc.Driver

// 引入外部资源文件,classpath:可以不写
@PropertySource("classpath:db.properties") 
public class IocJavaConfig {

    /**
     * 映射外部资源文件
      */
    @Value("${mysql.username}")
    private String name;
}

2.2.5、Import

1、引入别的JavaConifg配置类
2、可以将类注册为Bean

@Import(SecondIocJavaConfig.class)
public class IocJavaConfig {
}

@ComponentScan(basePackages = "cool.ale")
public class SecondIocJavaConfig {

}

// Test
AnnotationConfigApplicationContext  ioc = new AnnotationConfigApplicationContext(IocJavaConfig.class);
2.2.5.1、ImportSelector

可以以字符串的形式注册多个Bean,字符串必须是类的完整限定名,getBean不能根据名字获取,必须根据类型获取

@Component
public class MyImportSelector implements ImportSelector {
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{"cool.ale.entity.Person", Wife.class.getName()};
    }
}

// Test
@Test
public void test04(){
    Person bean = ioc.getBean(Person.class);
    System.out.println(bean.getName());

    Wife wife = ioc.getBean(Wife.class);
    System.out.println(wife.getName());
}
2.2.5.2、ImportBeanDefinitionRegistrar

导入ImportBeanDefinitionRegistrar,可以注册多个BeanDefinition

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        genericBeanDefinition.setBeanClass(Person.class);
        registry.registerBeanDefinition("person",genericBeanDefinition);
    }
}

// Test
@Test
public void test05(){
    Person bean = ioc.getBean(Person.class);
    System.out.println(bean.getName());
}

2.3、自动依赖

2.3.1、如何自动依赖外部Bean

在参数列表中直接添加即可。

@Bean
public DruidDataSource relyOn(Role role){
    DruidDataSource dataSource = new DruidDataSource();
    System.out.println(role.getName()+"duJiaLe");
    return dataSource;
}

// Test
AnnotationConfigApplicationContext  ioc = new AnnotationConfigApplicationContext(IocJavaConfig.class);
DruidDataSource bean = (DruidDataSource) ioc.getBean("relyOn");

2.3.2、如何自动依赖内部Bean

在同一个类中,直接调用即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值