SpringBoot相关概念

@Bean注解能干啥

  1. 产生对象,放入Spring容器中
    @Bean注解就是告诉Spring容器,产生一个Bean对象,交给Spring容器管理,产生这个Bean对象的方法Spring只会调用一次,随后Spring会将这个对象放在IOC容器。
  2. 实现自动注入解决依赖关系
    在这个过程中,Spring会自动处理该bean的依赖关系,并将需要注入的对象作为参数传递给该@Bean方法,实现自动注入。
    需要注意的是被注入的对象必须是在Spring中容器中声明过的对象,即被Spring容器管理,@Bean注解才能帮忙自动处理依赖关系,自动注入需要的对象

例子如下

  public class RedisConfig {
   @Bean
   public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
       System.out.println(factory);
       return null;
   }
}

对例子的解释,由于我的IOC容器中有RedisConnectionFactory 这个类,所以我可以直接写,而不需要用一些注解@Autowired等,因为我们使用了@Bean注解,就会自动解决当前这个Bean的依赖关系。(再次强调,自动解决依赖问题这个对象是必须在IOC容器中才可以,否则你需要将对象先加入到IOC容器中才可以进行 不懂的话,下面有这个解释 )

如何将对象注入到IOC容器中

使用配置类的方式

@Configuration
public class MyConfig {
 
    @Bean//这样就把目标类加入到了Spring的IOC容器中
    public TargetClass target() {
        return new TargetClass();
    }
}

Component注解的方式

除了@Component注解
@Service
@Controller
@Dao
都是可以的,他们都是把类作为Bean放到SpringIOC容器中进行管理,只不过是放在不同的层上

@Component
public class MyComponent {
 
    @Autowired
    private TargetClass target;
 
    // ...
}

你可能感兴趣的:(java,Springboot,spring,boot,spring,java)