Spring中Bean及@Bean的理解

Bean在Spring和SpringMVC中无所不在,将这个概念内化很重要,下面分享一下我的想法:

@Bean 只能用在方法上
一、Bean是啥
  1. Java面向对象,对象有方法和属性,那么就需要对象实例来调用方法和属性(即实例化);
  2. 凡是有方法或属性的类都需要实例化,这样才能具象化去使用这些方法和属性;
  3. 规律:凡是子类及带有方法或属性的类都要加上注册Bean到Spring IoC的注解;
  4. 把Bean理解为类的代理或代言人(实际上确实是通过反射、代理来实现的),这样它就能代表类拥有该拥有的东西了
  5. 我们都在微博上@过某某,对方会优先看到这条信息,并给你反馈,那么在Spring中,你标识一个@符号,那么Spring就会来看看,并且从这里拿到一个Bean或者给出一个Bean
二、注解分为两类:
  • 一类是使用Bean,即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;
比如@Autowired,@Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean
  • 一类是注册Bean
@Component,@Repository,@Controller ,@Service,@Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired, @Resource配合到一起,把对象、属性、方法完美组装。
三、@Bean是啥?

1、原理是什么?先看下源码中的部分内容:

Indicates that a method produces a bean to be managed by the Spring container.

 <h3>Overview</h3>

 <p>The names and semantics of the attributes to this annotation are intentionally
 similar to those of the {@code <bean/>} element in the Spring XML schema. For
 example:

 <pre class="code">
     @Bean
     public MyBean myBean() {
         // instantiate and configure MyBean obj
         return obj;
    }</pre>

  意思是@Bean明确地指示了一种方法,什么方法呢——产生一个bean的方法,并且交给Spring容器管理;从这我们就明白了为啥@Bean是放在方法的注释上了,因为它很明确地告诉被注释的方法,你给我产生一个Bean,然后交给Spring容器,剩下的你就别管了。
  

总结:

记住,@Bean就放在方法上,就是产生一个Bean。如果用@Bean来注解类,就是报not applicable type 的错误,如果你一定要注解类的话,可以通过使用
@Component,@Repository,@Controller ,@Service,@Configration代替。

例子:
结构

package com.minGW.domain;

/**
 * Created by Gracecoder on 2017/12/21.
 */
public class User {

    private String username;

    private String password;

    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

package com.minGW.Dao;

import com.minGW.domain.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//@Bean 只能用来注解方法 不能注解类,这里不用@Component 那就在配置文件中用@Bean 来注解方法获得Bean
@Component
public class UserDAO {

    public List<User> queryUserList(){
        List<User> result = new ArrayList<User>();
        // 模拟数据库的查询
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setUsername("username_" + i);
            user.setPassword("password_" + i);
            user.setAge(i + 1);
            result.add(user);
        }
        return result;
    }

}
package com.minGW.service;

import com.minGW.Dao.UserDAO;
import com.minGW.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Gracecoder on 2017/12/21.
 */

@Service
public class UserService {

    @Autowired // 注入Spring容器中的bean对象
    private UserDAO userDAO;

    public List<User> queryUserList() {
        // 调用userDAO中的方法进行查询
        return this.userDAO.queryUserList();
    }


}
package com.minGW.config;

import com.minGW.Dao.UserDAO;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Gracecoder on 2017/12/21.
 */

@Configuration  //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件
@ComponentScan(basePackages = "com.minGW.*") //配置扫描包
public class SpringConfig {

    //如果UserDao 用@Component注解过 这里就不需要再用@Bean
    @Bean // 通过该注解来表明是一个Bean对象,相当于xml中的<bean>
    public UserDAO getUserDAO(){
        return new UserDAO(); // 直接new对象做演示
    }

}
import com.minGW.config.SpringConfig;
import com.minGW.domain.User;
import com.minGW.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

/**
 * Created by Gracecoder on 2017/12/21.
 */
public class Main {
    public static void main(String[] args) {
        // 通过Java配置来实例化Spring容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        // 在Spring容器中获取Bean对象
        UserService userService = context.getBean(UserService.class);

        // 调用对象中的方法
        List<User> list = userService.queryUserList();
        for (User user : list) {
            System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPassword());
        }

        // 销毁该容器
        context.destroy();
    }

}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值