标签:*** tail .class 姓名 love 业务逻辑层 容器管理 index turn
适用场景:
<beans> <import resource=“resource1.xml” />//导入其他配置文件Bean的定义 <import resource=“resource2.xml” />
<bean id="userService" class="cn.lovepi.***.UserService" init-method="init" destory-method="destory"> </bean> <bean id="message" class="java.lang.String"> <constructor-arg index="0" value="test"></constructor-arg> </bean> </beans>
适用场景:
步骤如下:
1. 在applicationContext.xml配置扫描包路径
<context:component-scan base-package="com.lovepi.spring"> <context:include-filter type="regex" expression="com.lovepi.spring.*"/> //包含的目标类 <context:exclude-filter type="aspectj" expression="cn.lovepi..*Controller+"/> //排除的目标类 </context:component-scan>
注:<context:component-scan/> 其实已经包含了 <context:annotation-config/>的功能
2. 使用注解声明bean
Spring提供了四个注解,这些注解的作用与上面的XML定义bean效果一致,在于将组件交给Spring容器管理。组件的名称默认是类名(首字母变小写),可以自己修改:
@Service
public class SysUserService {
@Resource
private SysUserMapper sysUserMapper;
public int insertSelective(SysUser record){
return sysUserMapper.insertSelective(record);
}
}
适用场景:
步骤如下:
@Configuration
public class BeansConfiguration {
@Bean
public Student student(){
Student student=new Student();
student.setName("张三");
student.setTeacher(teacher());
return student;
}
@Bean
public Teacher teacher(){
Teacher teacher=new Teacher();
teacher.setName("李四");
return teacher;
}
}
public class Main {
public static void main(String args[]){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfiguration.class);
Student student = (Student) context.getBean("student");
Teacher teacher = (Teacher) context.getBean("teacher");
System.out.println("学生的姓名:" + student.getName() + "。老师是" + student.getTeacher().getName());
System.out.println("老师的姓名:" + teacher.getName());
}
}
参考:https://blog.csdn.net/lzh657083979/article/details/78524489
标签:*** tail .class 姓名 love 业务逻辑层 容器管理 index turn
原文地址:https://www.cnblogs.com/wslook/p/9161560.html