标签:div bean default 组件 类型 自动 import ima stat
package com.tanlei.dao; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; @Component或者是@Repository public class CustomerDao { @Override public String toString() { // TODO Auto-generated method stub return "hello ,this is CustomerDao"; } }
package com.tanlei.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.tanlei.dao.CustomerDao; @Component或是@Service public class CustomerService { @Autowired CustomerDao customerDao; @Override public String toString() { // TODO Auto-generated method stub return "CustomerService [customerDAO=" + customerDao + "]"; } }
将这个“context:component”在bean配置文件,这意味着,在 Spring 中启用自动扫描功能。base-package 是指明存储组件,Spring将扫描该文件夹,并找出Bean(注解为@Component)并注册到 Spring 容器。
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.tanlei.service"></context:component-scan> <context:component-scan base-package="com.tanlei.dao"></context:component-scan> </beans>
package com.tanlei.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tanlei.service.CustomerService; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans-spring.xml" }); CustomerService cust = (CustomerService) context.getBean("customerService"); System.out.println(cust); } }
要创建组件的自定义名称,你可以这样自定义名称:
@Service("AAA") public class CustomerService ...
现在,可以用‘AAA‘这个名称进行检索。
CustomerService cust = (CustomerService)context.getBean("AAA");
因此,使用哪一个?其实并不那么重要。参见 @Repository,@Service 或 @Controller 源代码。
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Repository { String value() default ""; }
你可能会发现,所有的 @Repository, @Service 或 @Controller 被注解为 @Component。因此,我们可以只使用 @Component 对所有组件进行自动扫描?是的,Spring会自动扫描所有组件的 @Component 注解。
标签:div bean default 组件 类型 自动 import ima stat
原文地址:https://www.cnblogs.com/tanlei-sxs/p/10132559.html