Spring如何將bean添加到容器中
spring的一大功能是依賴注入 通過把javabean放入spring的ioc容器中進(jìn)行統(tǒng)一管理
過程如圖所示

最常見的例子是使用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>
實例化一個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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java注解的Retention和RetentionPolicy實例分析
這篇文章主要介紹了Java注解的Retention和RetentionPolicy,結(jié)合實例形式分析了Java注解Retention和RetentionPolicy的基本功能及使用方法,需要的朋友可以參考下2019-09-09
Java中的FileInputStream是否需要close問題
這篇文章主要介紹了Java中的FileInputStream是否需要close問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Springsecurity Oauth2如何設(shè)置token的過期時間
如果用戶在指定的時間內(nèi)有操作就給token延長有限期,否則到期后自動過期,如何設(shè)置token的過期時間,本文就來詳細(xì)的介紹一下2021-08-08

