前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >@component使用案例

@component使用案例

作者头像
全栈程序员站长
发布2022-06-30 13:29:48
2370
发布2022-06-30 13:29:48
举报
文章被收录于专栏:全栈程序员必看

@component的作用是将一个java类加入到spring容器中管理,省去了<bean id=”” class=””>这句配置,取而代之的是<context component-scan base-package=”包名” />,负责扫描改包下的所有包名。

案例:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
  http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/aop   
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx   
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/context   
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/util   
  http://www.springframework.org/schema/util/spring-util-4.0.xsd
  ">
      	
     <context:component-scan base-package="com.aa"></context:component-scan>
      		
</beans>  
代码语言:javascript
复制
package com.aa;

import org.springframework.stereotype.Component;
import com.introduce.Model.User2;
@Component("impl")
public class UserDaoImpl {
	public User2 getUser2() {
		
		return null;
	}
	public User2 getUser2(String name) {
		User2 user2=new User2();
		user2.setAge(22);
		System.out.println(name+"s1");
		return  user2;
	}
	
	public void aa(){
		System.out.println("bbbbb");
	}
}
代码语言:javascript
复制
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.aa.UserDaoImpl;

public class Test4 {
	@Autowired
	private UserDaoImpl userDaoImpl;
	@Test
	public void test() {
		//启动spring容器,因为是测试类,所以要使用applicationContext.如果是tomcat启动就不用。
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext5.xml");
		userDaoImpl=(UserDaoImpl) ac.getBean("impl");
		userDaoImpl.aa();
	}

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/106264.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年7月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档