溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring將bean添加到容器中的方法

發(fā)布時間:2020-07-28 14:27:57 來源:億速云 閱讀:310 作者:小豬 欄目:編程語言

這篇文章主要講解了Spring將bean添加到容器中的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

spring的一大功能是依賴注入 通過把javabean放入spring的ioc容器中進(jìn)行統(tǒng)一管理

過程如圖所示

Spring將bean添加到容器中的方法

最常見的例子是使用xml配置bean 把每一個<bean>元素分別轉(zhuǎn)換成一個BeanDefinition對象,其中保存了從配置文件中讀取到的該bean的各種信息

再通過BeanFactory對bean進(jìn)行注冊 關(guān)于BeanFactory請看這篇文章 https://www.cnblogs.com/aspirant/p/9082858.html

例如:

<!--配置mybatis的mapper掃描包-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="myblog.dao"></property>
  </bean>

實(shí)例化一個bean 并加入容器中

有兩種方法

a.在要加入容器的bean上加@component

并指定掃描該類所在的包

例如:

@Service
@Transactional
public class BlogServiceImpl implements BlogService {
  @Autowired
  private BlogDao blogDao;
  @Override
  public List<Blog> findAll() {
    return blogDao.findAll();
  }

  @Override
  public void insertUserAndBlog(Integer blogId, Integer userId) {
    blogDao.insertUserAndBlog(blogId,userId);
  }

  @Override
  public void insertBlog(Blog blog) {
    blogDao.insert(blog);

  }

  @Override
  public void update(Blog blog) {
    blogDao.update(blog);
  }

  @Override
  public void delete(Blog blog) {
   blogDao.delete(blog);
  }

  @Override
  public Blog findById(Integer id) {
    PageHelper.startPage(1, 6);
    return blogDao.findById(id);
  }

  @Override
  public List<Blog> findBlogByUserId(Integer userId) {
    PageHelper.startPage(1, 6);
    return blogDao.findBlogByUser(userId);
  }
}

b.在配置類中使用@bean進(jìn)行注冊

例如:

@Configuration
public class ApplicationContextConfig {
  @Bean
  @LoadBalanced
  public RestTemplate getRestTemplate(){
    RestTemplate restTemplate=new RestTemplate();
    return restTemplate;
  }
}

看完上述內(nèi)容,是不是對Spring將bean添加到容器中的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI