【spring】Spring中有几种配置方式(xml、注解<jsr250>、JavaConfig)


相关文章:

Spring中有几种配置方式(xml、注解<jsr250>、JavaConfig)讲述了spring的三种配置形式
【spring注解】context:annotation-config和context:component-scan区别 解释了开启注解形式的配置语法
【spring4.0】@Configuration、@Bean的使用
【spring】JavaConfig、@Configuration、@ComponentScan入门例子

概述

将 Spring 配置到应用开发中有以下三种方式:

  • 基于xml配置:通常一开头
  • 基于注解配置:@Controller @Service @Autowired @RequestMapping @RequestParam @ModelAttribute @Cacheable @CacheFlush @Resource @PostConstruct @PreDestroy @Repository @Scope @SessionAttributes @InitBinder @Required @Qualifier
  • 基于java配置:@Configuration、@Bean,当然,也兼容第二种形式

1. 如何用XML配置Spring

xml有2种语法,dtd和xsd,详情参见《Spring xml配置dtd及xsd格式解析

  • 在 Spring 框架中,依赖和服务需要在专门的配置文件来实现,我常用的 XML 格式的配置文件。这 些配置文件的格式通常用开头,然后一系列的 bean 定义和专门的应用配置 选项组成。

  • SpringXML 配置的主要目的时候是使所有的 Spring 组件都可以用 xml 文件的形式来进行配置。这 意味着不会出现其他的 Spring 配置类型(比如声明的方式或基于 Java Class 的配置方式)

  • Spring 的 XML 配置方式是使用被 Spring 命名空间的所支持的一系列的 XML 标签来实现的。 Spring 有以下主要的命名空间:context、beans、jdbc、tx、aop、mvc 和 aso。
    如:

<beans>
         <!-- JSON Support -->
         <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
         <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonV iew"/>
         <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>     
</beans>


2. 怎样用注解的方式配置 Spring?

建议先阅读《context:annotation-config和context:component-scan区别》

Spring 在 2.5 版本以后开始支持用注解的方式来配置依赖注入。可以用注解的方式来替代 XML 方 式的 bean 描述,可以将 bean 描述转移到组件类的 内部,只需要在相关类上、方法上或者字段声 明上使用注解即可。注解注入将会被容器在 XML 注入之前被处理,所以后者会覆盖掉前者对于同一 个属性的处理结 果。

注解的初衷是简化xml配置的,因此不能单独存在,比如下面要通过开关打开。而且,有些配置不方便用注解解决,比如jdbc的连接池,仍需xml配置。

注解装配在 Spring 中是默认关闭的。所以需要在 Spring 文件中配置一下才能使用基于注解的装配 模式。如果你想要在你的应用程序中使用关于注解的方法的话,请参考如下的配置:

<beans>
        <context:annotation-config/>        
        <!-- bean definitions go here -->     
</beans> 

<context:annotation-config/>标签配置完成以后,就可以用注解的方式在 Spring 中向属 性、方法和构造方法中自动装配变量。

下面是几种比较重要的注解类型,分为2类:

  • 负责bean定义
    在bean的上面使用@Component或其子类(@Repository、@Service、@Controller)来定义bean

  • 负责Bean的注入

    • @Required:该注解应用于设值方法。
    • @Autowired:该注解应用于有值设值方法、非设值方法、构造方法和变量。
    • @Qualifier:该注解和@Autowired 注解搭配使用,用于消除特定 bean 自动装配的歧义。
    • JSR-250 Annotations:Spring 支持基于 JSR-250 注解的以下注解,@Resource、 @PostConstruct 和 @PreDestroy。

    jsr250参见《Spring 注解支持的JSR 250规范》

注解的配置原则是:基本配置使用xml(如数据库的配置),业务配置使用注解。

举例:
先由控制层(Controller)调用服务层(Service),再由服务层调用Dao层(数据访问层),使用注解如下:

控制层:UserController.java:

@Controller
public class UserController {
    @Autowired  //自动装配
    private UserService userService;
    
    //保存用户
    public String save(User user) {
        userService.save(user);
        return "保存成功";
    }
}

服务层Service:UserService.java:

@Service
public interface UserService {

    //保存用户
    void save(User user);
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;


    @Override
    public void save(User user) {
        userDao.save();
    }
}

Dao层:UserDao.java:

@Repository
public interface UserDao{
    void save();
}

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        //保存数据的操作
    }
}

3. 基于JavaConfig的配置

Spring3.0以后,提供了Java配置的能力,Spring4.x和SpringBoot都推荐使用Java配置。

基于java的配置,简单来说是通过提供新的注解标签,提供完全替代xml的解决方案,以后可以不用类似aplication.xml作为配置入口了。
xml=注解+javaConfig

首先要说明以下两个注解:

  • @Configuration,表示修饰的类可以作为bean的来源(通过注解来获取bean,等价于aplication.xml的作用,作为入口类)
  • @Bean,表示实例化一个bean,等同于在xml里面添加一个bean 被@Bean修饰的方法名就是该bean的name

最简单的@Configuration 声明类请参考下面的代码:

@Configuration     
public class AppConfig{
         @Bean         
         public MyService myService() {
                return new MyServiceImpl();
         }     
} 

对于上面的@Beans 配置文件相同效果的 XML 配置文件如下:

<beans>         
		<bean id="myService" class="com.somnus.services.MyServiceImpl"/>     
</beans>  

上述配置方式的实例化方式如下:利用 AnnotationConfigApplicationContext 类进行实例化

public static void main(String[] args) {
         ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);         
         MyService myService = ctx.getBean(MyService.class);         
         myService.doStuff();     
}

要使用组件组建扫描,仅需用@ComponentScan进行注解即可:

@Configuration     
@ComponentScan(basePackages = "com.somnus")     
public class AppConfig  {         ...     }   

在上面的例子中,com.acme 包首先会被扫到,然后再容器内查找被@Component 声明的类,找 到后将这些类按照 Sring bean 定义进行注册。

如果你要在你的 web 应用开发中选用上述的配置的方式的话,需要用 AnnotationConfigWebApplicationContext 类来读 取配置文件,可以用来配置 Spring 的 Servlet 监听器 ContextLoaderListener 或者 Spring MVC 的 DispatcherServlet:

<web-app>
         <!-- 配置 ContextLoaderListener 时用 AnnotationConfigWebApplicationContext 替代默认的 XmlWebApplicationContext -->         
         <context-param>
       		 <param-name>contextClass</param-name>             
             <param-value>
                     org.springframework.web.context.support.AnnotationConfigWebApplicationContext             
             </param-value>
         </context-param>
               <!-- Configuration locations must consist of one or more comma- or space-delimited    
               fully-qualified @Configuration classes. Fully-qualified packages may also be         
               specified for component-scanning -->
         <context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>com.howtodoinjava.AppConfig</param-value>
         </context-param>
         
               <!-- Bootstrap the root application context as usual using ContextLoaderListener -->    
         <listener>
             <listenerclass>org.springframework.web.context.ContextLoaderListener</listener -class>
         </listener>
               <!-- Declare a Spring MVC DispatcherServlet as usual -->
         <servlet>
             <servlet-name>dispatcher</servlet-name>
             <servletclass>org.springframework.web.servlet.DispatcherServlet</servletclass>
             <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext -->
             <init-param>
                 <param-name>contextClass</param-name>
                 <param-value>
                     org.springframework.web.context.support.AnnotationConfigWebApplicationContext
                 </param-value>
             </init-param>
             <!-- Again, config locations must consist of one or more comma- or space-delimited and fully-qualified @Configuration classes -->
             <init-param>
                 <param-name>contextConfigLocation</param-name>
                 <param-value>com.howtodoinjava.web.MvcConfig</paramvalue>
             </init-param>
         </servlet>
               <!-- map all requests for /app/* to the dispatcher servlet -->
         <servlet-mapping>
             <servlet-name>dispatcher</servlet-name>
             <url-pattern>/app/*</url-pattern>
         </servlet-mapping>     
</web-app     


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中有多种方式来定义和管理bean的生命周期。其中包括使用XML配置注解和使用JSR250中的@PostConstruct和@PreDestroy注解。 1. XML配置方式:在XML配置文件中,可以使用<bean>标签来定义bean,并通过指定init-method和destroy-method属性来指定bean的初始化和销毁方法。例如: ```xml <bean id="user" class="com.demo.pojo.User" init-method="init" destroy-method="destroy"> </bean> ``` 在这个例子中,init-method属性指定了bean的初始化方法为"init",destroy-method属性指定了bean的销毁方法为"destroy"。 2. 注解方式:使用注解可以更简洁地定义bean的生命周期。可以使用注解@Bean来标注一个方法,该方法返回一个bean实例,并可以使用@PostConstruct和@PreDestroy注解来指定初始化和销毁方法。例如: ```java @Configuration public class AppConfig { @Bean(initMethod = "init", destroyMethod = "destroy") public User user() { return new User(); } } ``` 在这个例子中,@Bean注解标注的方法user()返回一个User实例,并通过initMethod和destroyMethod属性指定了初始化和销毁方法。 3. 使用JSR250中的@PostConstruct和@PreDestroy注解:可以在bean类中使用@PostConstruct和@PreDestroy注解来标注初始化和销毁方法。例如: ```java public class User { @PostConstruct public void init() { // 初始化方法的逻辑 } @PreDestroy public void destroy() { // 销毁方法的逻辑 } } ``` 在这个例子中,@PostConstruct注解标注的方法init()会在bean初始化之后调用,@PreDestroy注解标注的方法destroy()会在bean销毁之前调用。 总结起来,Spring提供了多种方式来定义和管理bean的生命周期,包括XML配置注解和使用JSR250中的@PostConstruct和@PreDestroy注解。这些方式可以根据具体的需求和项目的特点来选择和使用。[1][2][3]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值